gpt4 book ai didi

java - 使用抽象类实现接口(interface)

转载 作者:行者123 更新时间:2023-11-29 05:02:54 25 4
gpt4 key购买 nike

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

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 原则,最好的表达方式是什么?两种方法的接口(interface)似乎并不合适。以下是我提出的选项:

  1. 列出接口(interface)上的所有方法,无论实现是否相同。然后为共享的 erase() 实现使用一个抽象类。这对我来说似乎是最好的解决方案,因为 EraseableColoredPencil 将需要实现 erase()这允许所有类共享相同的实现。我知道这是可能的,但我担心它是否遵循最佳实践。
  2. 消除接口(interface)并使用抽象类。这似乎没有遵循良好的设计模式,但可以保证每个扩展类都具有适当的方法,甚至具有一致的实现,直到给定的方法被覆盖。
  3. 保持原样。可能是我想多了,这确实是一个不错的方法。
  4. Something Else. 我确定我错过了什么。有更好的方法吗?

最佳答案

  1. 其他:关注 Interface Segregation Principle并拆分界面:

    interface Drawer{
    void draw();
    }

    interface Erasable {
    void erase();
    }

    interface EraseableDrawer extends Drawer, Erasable {
    }

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

    如果 erase() 对于所有或大多数类来说确实是相同的实现,您仍然可以使用实现了 ErasableDrawer 的抽象类 AbstractErasableDrawer使用 erase() 的具体实现(或使用默认实现 as suggested above )

关于java - 使用抽象类实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com