当前位置: 代码迷 >> java >> 使用抽象类实现接口
  详细解决方案

使用抽象类实现接口

热度:110   发布时间:2023-07-26 14:49:16.0

我有一个界面。 为了这个问题,我将它简化为:

interface EraseableColoredPencil {

  //This method seems appropriate for an interface;
  //The implementation will change with each class that implements this interface.
  void draw();

  //This method does not seem as appropriate;
  //The implementation of the erase method would be the same for all classes.
  void erase();
}

我的问题是: 根据OOP原则,表达这一点的最佳方式是什么? 两种方法的接口似乎都不合适。 以下是我提出的选项:

  1. 在接口上列出所有方法,无论实现是否相同。 然后使用抽象类进行共享erase()实现。 这对我来说似乎是最好的解决方案,因为EraseableColoredPencil将需要实现erase() ,这允许所有类共享相同的实现。 我知道这是可能的,但我关心的是它是否遵循最佳实践。
  2. 消除接口并使用抽象类。 这似乎不符合良好的设计模式,但可以保证每个扩展类都具有适当的方法,甚至可以实现一致的实现,直到覆盖给定的方法。
  3. 离开原样。 我可能会过度思考这个问题,这确实是一种可行的方法。
  4. 还有别的。 我确定我错过了什么。 有一个更好的方法吗?
  1. 其他:遵循并拆分界面:

     interface Drawer{ void draw(); } interface Erasable { void erase(); } interface EraseableDrawer extends Drawer, Erasable { } 

    现在你只需要依赖DrawerErasable ,这取决于你真正需要的方法(如果你需要两者,可以选择ErasableDrawer )。

    如果erase()对于所有或大多数类实际上是相同的实现,您仍然可以使用抽象类AbstractErasableDrawer实现ErasableDrawer并使用erase()的具体实现(或使用的默认实现)

正如您现在只是询问Java,有第三个选项,Java 8提供: 。

这允许您使用接口并定义erase的默认行为,从而不再需要抽象类:

interface EraseableColoredPencil {

    void draw();

    default void erase() { ... }
}
  相关解决方案