编程语言
首页 > 编程语言> > java – 在特定示例中删除代码重复

java – 在特定示例中删除代码重复

作者:互联网

我有三种重复代码的方法.
前两种方法几乎完全重复.第三个与火灾略有不同,应该绘制更多的信息.

我想删除这个重复的代码,并考虑使用内部类的模板方法模式.这是正确的方法还是有更好的解决方案?

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
    }
}

解决方法:

在我看来,你的物品集合(火,水供应等)并不像它们应该的那样聪明.理想情况下,您应该能够说:

for (Fire f : groundMap.getFires()) {
   f.draw(g);
}

并且每个对象都能够定位自己(使用它的位置),大小本身(因为Fire知道它将使用FireImage等)并将自己绘制到提供的Graphics对象上.

为了更进一步,我希望将Graphics对象传递给你的groundMap:

groundMap.drawFires(g);

我们的想法是,在OO中,您不应该向对象询问其详细信息,然后再做出决策.相反,你应该告诉对象为你做事.

标签:java,code-duplication
来源: https://codeday.me/bug/20190729/1571042.html