gpt4 book ai didi

java - 为什么父类和子类都实现相同的接口(interface)?

转载 作者:IT老高 更新时间:2023-10-28 21:12:04 32 4
gpt4 key购买 nike

我继承了一些遗留的 Java (1.4) 代码,并且这个设计决策经常出现。我不明白这是否有任何目的或理由。

public interface SoapFacade extends iConfigurable{ }

public class SoapFacadeBase implements SoapFacade{
...
}

public class SoapFacadeImpl extends SoapFacadeBase implements SoapFacade{
...
}

根据我对接口(interface)的理解(并且我的实验得到了加强),让父级和子级都实现相同的接口(interface)是没有意义的。在这种情况下,SoapFacade 中的所有内容都在 SoapFacadeBase 中实现,但 iConfigurable 中的方法在 SoapFacadeImpl 中实现。但是,这并不需要 SoapFacadeImpl 实现 SoapFacade

有没有什么我不知道的接口(interface)可以给这个模式一些目的或好处?除了缺乏明确性之外,是否还有潜在的成本应该插入重构?还是应该为了清晰/简单而简单地对其进行重构?

最佳答案

As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface.

没有。从技术上讲,它是完全多余的。

确实但是记录了您打算将 SoapFacadeImpl 成为 SoapFacade 的事实,并且它确保您收到编译错误,如果您(或其他人)决定从基类中删除 implements SoapFacade

您在标准 Java 集合 API 中随处可见这种模式。 ArrayList 实现了 List,尽管它的基类 (AbstractList) 已经实现了。 HashSet/AbstractSetSet 接口(interface)也是如此。

关于java - 为什么父类和子类都实现相同的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668429/

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