我在代码重用和代码结构的几种不同 OOP 方法之间左右为难,我无法找出适合我的情况的最佳选择。
目前,我有一个名为“地 block ”(一 block 土地)的基类,它处理标准地 block 类型和任何其他地 block 类型的核心功能。所以我认为使用核心绘图功能扩展 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 基类的功能。
所以在这一点上,我知道我应该使用接口(interface)继承而不是实现继承。或许我可以让 Plot 成为定义所有绘图类型(标准、庄园等)核心功能的接口(interface)。现在这就是我被困的地方,因为我面临着代码重用的问题。我不想为所有 Plot 类型实现相同的标准功能,所以我考虑使用一种过程类(我们称之为 PlotHelper),它定义了公共(public)静态方法来处理给定 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 的公共(public)静态方法中的功能点和片段过去在基 Plot 类中一起处理,这意味着更多的模块化和内部化代码。
最后,既然您知道我在哪里以及为什么被卡住了,是否有任何首选解决方案可以避免实现继承并保持类型特定代码的内部化?或者您可以想出一种完全不同的方法来处理这种情况。
感谢您的宝贵时间!
最佳答案
Abstract classes允许您实现一个方法(代码可重用性)并声明抽象方法(接口(interface)继承)。
然后,您可以在 Plot
抽象类中实现一个 doStuff()
方法,并创建一个类似 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
类及其子类调用。
关于java - 在避免实现继承和保持内部化的同时最大化代码重用的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550476/