【问题标题】:Is it okay for two or more interfaces to have the same methods?两个或多个接口具有相同的方法可以吗?
【发布时间】:2018-10-13 17:35:42
【问题描述】:

我正在用Java制作一个简单的游戏,我有这个疑问。

假设每个游戏角色都有一个界面

public interface Entity{
   Vector2 getPosition();
   /* More methods...*/
}

然后我想创建一个名为 Automata 的接口,由每个使用 AI 东西的类实现(这可能是 Entity 的一个特例,但由于可重用性,我单独考虑了它)

public interface Automata{
  Vector2 getPosition(); // The AI stuff needs to know this
  /* More methods needed for AI (some may also be the same as Entity)... */
}

我认为这促进了模块化,因为每个接口都描述了它的方法而不用担心其他接口的存在,但是当我写这篇文章时,我觉得我在重复自己,拥有这两个(或可能更多)接口也是如此用同样的方法有什么不好的吗?

【问题讨论】:

  • 这取决于语义,如果这两个方法应该具有相同的含义,您可以在由其他两个扩展的第三个接口中定义它。

标签: java oop interface


【解决方案1】:

如果两个接口之间有一些共同点,那么也许你可以定义一个父接口,然后EntityAutomata 可以扩展它。

下面我来说明一下:

interface AI {
    Vector2 getPosition();
}

interface Entity extends AI { }
interface Automata extends AI { }

这样,作为 AI 一部分的任何其他接口都不需要显式添加其他方法,而只需扩展 AI

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 2013-07-03
    • 2020-12-09
    • 1970-01-01
    • 2011-07-26
    • 2018-11-04
    • 1970-01-01
    • 2022-01-22
    • 2015-05-01
    相关资源
    最近更新 更多