最大化代码重用的方法,同时避免实现继承和维护内部化

时间:2014-10-24 14:52:59

标签: java oop design-patterns

我在代码重用和代码结构的几种不同的OOP方法之间徘徊,我无法为我的案例找出最佳选择。

目前,我有一个名为' Plot' (一块土地),处理标准绘图类型和任何其他绘图类型的核心功能。所以我认为有任何其他Plot类型使用核心绘图功能来扩展Plot是有意义的。但是,我现在意识到这种方法有许多垮台。这是我的代码的当前基本结构(在java中):

public class Plot {
    public void doStuff() {
        // Do stuff for Standard plot type
    }
}

public class EstatePlot extends Plot {
    @Override
    public void doStuff() {
        // Make sure we still handle the base functionality (code reuse)
        super.doStuff();

        // Make sure we also do stuff specific to the Estate plot type
    }

    public void extendedFunctionality() {
        // Do stuff that only applies to the Estate plot type
    }
}

出于几个原因,我不喜欢这种方法。

  • 在某些情况下,我需要覆盖方法以提供更多功能,但我不想执行父方法中的所有代码。 (即:没有控制或精确的代码重用)
  • 类之间存在强大的功能耦合。 (即:基础Plot类可能对任何子类行为产生不良影响,因为它们是紧密耦合的。这被称为脆弱的基类问题)

我认为这种方法不合适的更多理由可以在这里找到(http://www.javaworld.com/article/2073649/core-java/why-extends-is-evil.html

我考虑过使用Composition,但我意识到这不是一个好选择,因为我仍然需要覆盖基础Plot类的功能。

所以在这一点上,我知道我应该使用接口继承而不是实现继承。也许我可以创建一个界面来定义所有绘图类型(标准,房地产等)的核心功能。现在这就是我被困的地方,因为我面临着代码重用的问题。我不想为所有Plot类型实现相同的标准功能,所以我考虑使用一种过程类(让我们称之为PlotHelper)定义公共静态方法来处理给定Plot对象的许多核心功能。这是一个例子:

public interface Plot {
    public void doStuff();
}

public class StandardPlot implements Plot {

    @Override
    public void doStuff() {
        PlotHelper.handleStuff(this);
    }
}

public class EstatePlot implements Plot {
    @Override
    public void doStuff() {
        // Make sure we still handle the base functionality (code reuse)
        PlotHelper.handleStuff(this);

        // Make sure we also do stuff specific to the Estate plot type
    }

    public void extendedFunctionality() {
        // Do stuff that only applies to the Estate plot type
    }
}

public class PlotHelper {
    public static void handleStuff(Plot plot) {
        // Do stuff for Standard plot type
    }
}

我的问题是现在核心功能已不再内化。现在在PlotHelper中的公共静态方法中的位和功能拼凑过去一起在基础Plot类中处理,这意味着更多的模块化和内化代码。

所以最后,既然你知道我被困在哪里以及为什么,是否有任何首选的解决方案可以避免实现继承并保持特定类型代码的内部化?或许你可以想到一种完全不同的方法,对于这种情况来说是很好的。

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

也许Template Pattern适用于您?

答案 1 :(得分:1)

Abstract classes允许您实现一个方法(代码可重用性)并声明抽象方法(接口继承)。

然后,您可以在doStuff()抽象类中实现Plot方法,并创建一个类似doSpecificStuff()的抽象方法,以便在PlotType中实现。

public abstract class Plot {
    protected void doStuff(){
        //Implement general stuff for Plot
    };

    abstract void doSpecificStuff();
}

public class StandardPlot extends Plot {

    @Override
    public void doSpecificStuff() {
        // Make sure we still handle the base functionality (code reuse)
        doStuff(); //if needed. You can call standardPlot.doStuff() and then
                   //standardPlot.doSpecificStuff();

        // Make sure we also do stuff specific to the Estate plot type
    }

    public void extendedFunctionality() {
        // Do stuff that only applies to this plot type
    }
}

抽象类无法实例化,因此您仍然需要StandardPlot类。同时将doStuff()声明为protected,确保该方法仅由Plot类及其子类调用。