问。如果您在未链接到接口(interface)的抽象类中创建抽象方法,您是否仍在遵循对接口(interface)编程的原则?
我已经为我创建的所有 UI 类使用了一个接口(interface);但是,考虑到接口(interface)的原因,我没有看到与我要创建的抽象方法和已经存在的接口(interface)有直接关联。
通常,我会创建抽象方法并完成;但是,我想知道我是否违反了Program to an Interface 的设计原则。
问。我应该为此创建另一个接口(interface)还是坚持使用抽象方法?
注意:这不是接口(interface)与抽象类的问题。
public abstract class BaseClass extends Clazz implements Interface {
// 1 out of 4 interface methods are implemented here
CustomObj getMode() { ... }
// I am actually also thinking of taking that 1 method - getMode() - out of the
// interface and implementing it as an implemented method without an interface.
// Method that made me ask this question!!
abstract CustomObj getDefaultMode(); // Not related to the interface - Interface
}
public interface Interface {
String getFirstNumber();
String getSecondNumber();
CustomObj getMode(); // This one is implemented in the BaseClass, but I think it no longer belongs in this role
// CustomObj getDefaultMode(); // This one is not in Interface, but makes be believe I need a new Interface or just have them declared in an Abstract Class.
}
注意:我的基类更多是为了简化具体类中的代码。基类处理一些重写方法、辅助方法、初始化等...因此它不像接口(interface)那样工作,而是作为您的标准抽象类。
最佳答案
问。如果您在未链接到接口(interface)的抽象类中创建抽象方法,您是否仍在遵循 Program to Interface 的原则?
A:抽象类也是一种接口(interface)**。这取决于您如何使用它:如果您将它用作某种接口(interface) - 那么您仍然遵守原则。如果抽象类是一种在后代之间重用代码的技术工具 - 那么这是一种违规行为。
您始终可以添加 Interface2 extends Interface
来反射(reflect)此方法的额外功能。您提到了这个选项 - 如果抽象类不是“接口(interface)”,它可能有意义。
有一种为不同的访问级别创建层次结构接口(interface)的模式。例如:
User
界面 - 用户详细信息的只读访问UserMaintainance 扩展了 User
接口(interface) - 还允许更新用户详细信息。
看来您的情况可能属于这个定义。
** 例如,在对 SPI 进行编程时,有时将接口(interface)作为抽象类会更好,这样您就可以保持对旧版本的向后兼容性。
关于java - 创建新的抽象方法与接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343249/