0

假设我有一个接口 C 和一个实现它的类 A。

现在假设我想将 A 的实现更改为 C 中的所有函数,除了一个,使用类 B。我应该扩展 A 并覆盖 C 还是应该将 C 实现为新的独立类?

假设一些电话公司想要实现他们的基本接口 Phone 并且他们已经有一些 OldPhone 的旧实现,他们希望保留它的所有功能:拨打电话、挂断、发送 SMS - 而他们不想要改变这一切,但他们确实希望其他新功能来制造他们的新智能手机——他们应该扩展 OldPhone 还是创建一个新类?

我想知道什么时候应该扩展类,什么时候应该从一开始就实现接口——一方面我不想复制代码,但另一方面有时类型,即使它们都是 A,也是概念上不同。

4

5 回答 5

2

If there is shared functionality in OldPhone and SmartPhone you could extract that into a (abstract)class and let both extend that and let them have the other as diffrences.

Otherwise go for interface

于 2013-06-19T14:50:14.153 回答
2

If you have code which you want to reuse, then extending is the better choice.

But ask yourself: is the new phone a better version of the old one or a completely new one just with similiar functions?

  • In the first case: extending.
  • In the second abstraction is what you're searching for: extract the functions the have in common and put them in an abstract class, which both classes will extend.
于 2013-06-19T14:50:23.050 回答
2

It rather depends on how much changes from C (old phone) to B (new phone). Using phones as an example is quite good because an old phone conceptually does the same as a new phone - it makes phone calls.

The difficultly comes when the implementation of C is tied very tightly to how the phone works. Lets say for example that the old phone insists on using a circular ring that you turn to select the number to dial rather than a key pad. In that situation, if you have complete control of the code, then you might want to try and put in a layer of abstraction between the interface and the old phone. The abstraction layer would capture just what it means to be a phone and nothing more.

Once you have the abstraction layer you can then choose whether you extend the old phone to create your new phone or create a new implementation. Either way it should be easier than you have now as the old phone will contain far less code and only those bits that are specific to it.

于 2013-06-19T14:50:48.400 回答
2

现在看你的要求说 B 对于大多数功能应该表现得与 A 完全一样。现在假设您选择实现即 B 实现 C。那么如果将来 A 类逻辑发生更改,那么您还必须更改 B 类。所以它不符合您的要求。

现在假设你扩展了 A。但是你与 A 紧密耦合。好像 A 改变了你的 Big 也会以同样的方式表现。

所以尽量让两个词的使用发挥最大的作用。B 实现 C 并使用A 作为委托来实现这些方法。我的回答是,对于您的情况,它不一定是每种情况下的最佳选择。

于 2013-06-19T14:57:02.690 回答
1

经验法则,只有在存在父子关系时才应该扩展一个类。否则去接口实现。

于 2013-06-19T14:47:16.790 回答