Jon*_*son 6 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
}
}
Run Code Online (Sandbox Code Playgroud)
出于几个原因,我不喜欢这种方法.
我认为这种方法不合适的更多原因可以在这里找到(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
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是现在核心功能已不再内化.现在在PlotHelper中的公共静态方法中的位和功能拼凑过去一起在基础Plot类中处理,这意味着更多的模块化和内化代码.
最后,既然你知道我被困在哪里和为什么,是否有任何首选的解决方案可以避免实现继承并维护特定类型代码的内部化?或许你可以想到一种完全不同的方法,对于这种情况来说是很好的.
谢谢你的时间!
抽象类允许您实现方法(代码可重用性)并声明抽象方法(接口继承)。
然后,您可以在抽象类中实现一个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
}
}
Run Code Online (Sandbox Code Playgroud)
但抽象类无法实例化,因此您仍然需要一个StandardPlot
类。还要声明doStuff()
确保protected
该方法仅由Plot
类及其子类调用。