我有三种重复代码的方法。 前两种方法几乎完全重复。第三种情况与火灾有所不同,应该提供更多信息。删除特定示例中的代码重复
我想删除这个重复的代码,并考虑使用内部类的模板方法模式。这是正确的方式还是有更好的解决方案?
private void drawWaterSupplies(Graphics g) {
double hScale = getWidth()/(double) groundMap.getWidth();
double vScale = getHeight()/(double) groundMap.getHeight();
int imageOffsetX = waterSupplyImage.getWidth()/2;
int imageOffsetY = waterSupplyImage.getHeight()/2;
for (Location l : groundMap.getWaterSupplyLocations()) {
int x = (int) (l.getX() * hScale);
int y = (int) (l.getY() * vScale);
g.drawImage(waterSupplyImage, x - imageOffsetX, y - imageOffsetY,
null);
}
}
private void drawEnergySupplies(Graphics g) {
double hScale = getWidth()/(double) groundMap.getWidth();
double vScale = getHeight()/(double) groundMap.getHeight();
int imageOffsetX = energySupplyImage.getWidth()/2;
int imageOffsetY = energySupplyImage.getHeight()/2;
for (Location l : groundMap.getEnergySupplyLocations()) {
int x = (int) (l.getX() * hScale);
int y = (int) (l.getY() * vScale);
g.drawImage(energySupplyImage, x - imageOffsetX, y - imageOffsetY,
null);
}
}
private void drawFires(Graphics g) {
double hScale = getWidth()/(double) groundMap.getWidth();
double vScale = getHeight()/(double) groundMap.getHeight();
int imageOffsetX = fireImage.getWidth()/2;
int imageOffsetY = fireImage.getHeight()/2;
for (Fire fire : groundMap.getFires()) {
Location l = fire.getLocation();
int x = (int) (l.getX() * hScale);
int y = (int) (l.getY() * vScale);
g.drawImage(fireImage, x - imageOffsetX, y - imageOffsetY, null);
// TODO: draw status bar showing state of fire below
}
}
看起来不错。但是这不违反模型和表示的分离吗? – kobo
@ kobo - 有趣的一点。为了完全实现这种分离,我想你必须调查双重发送/访问者模式,例如Fire对象(比如说)和图形目标在它们自己之间进行调解以达到他们需要实现的图形 –
好吧,我试过了弄清楚这是如何工作的。 我会有一个访问接口的方法:'访问(Fire f)','访问(WaterSupply w)',... 然后,对于绘图,我将有一个'新的DrawingVisitor(Graphics g)',它实现访客界面来绘制对象。 这是不是你在说什么? – kobo