多重继承:什么是好的例子?
我试图找到一个使用多重继承的好例子,这是普通接口无法做到的。
我认为很难找到这样一个不能以其他方式建模的例子。
编辑:我的意思是,有人可以为我命名一个很好的现实世界示例,说明您何时需要使用多重继承来尽可能干净地实现此示例。而且它不应该使用多个接口,就像在 C++ 中继承多个类一样。
I'm trying to find a good example for the use of multiple inheritance what cannot be done with normal interfaces.
I think it's pretty hard to find such an example which cannot be modeled in another way.
Edit: I mean, can someone name me a good real-world example of when you NEED to use multiple inheritance to implement this example as clean as possible. And it should not make use of multiple interfaces, just the way you can inherit multiple classes in C++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是经典:
来源:wiki。
The following is a classic:
Source: wiki.
观察者模式是多类继承有意义的一个例子。该模式描述了两个参与者,观察者和可观察者,前者希望在后者改变其对象状态时得到通知。
在 C# 中,通知客户端的简化版本如下所示:
这基本上是通知所有注册观察者所需的核心逻辑。您可以通过从此类派生来使任何类可观察,但由于 C# 只支持单个类继承,因此您只能从另一个类派生。这样的事情是行不通的:
在这些情况下,您经常必须复制使子类在所有子类中可观察的代码,基本上违反了“不要重复自己”和“单点真理”原则(如果您在 C# 中使用了 MVVM,想一想:您多久实现一次
INotifyPropertyChanged
接口?)。在我看来,具有多个类继承的解决方案会更加清晰。在 C++ 中,上面的例子可以编译得很好。Bob叔叔写了一篇关于这个的有趣文章,那就是我从哪里得到这个例子。但这个问题通常适用于所有可*能的接口(例如,可比较、可等价、可枚举等):在这些情况下,多类继承版本通常更清晰,正如 Bertrand Meyer 在他的书《面向对象的软件构造》中所述”。
One example where multiple class inheritance makes sense is the Observer pattern. This pattern describes two actors, the observer and the observable, and the former wants to be notified when the latter changes its object state.
A simplified version for notifying clients can look like this in C#:
This basically is the core logic you need to notify all the registered observers. You could make any class observable by deriving from this class, but as C# does only support single class inheritance, you are limited to not derive from another class. Something like this wouldn't work:
In these cases you often have to replicate the code that makes subclasses observable in all of them, basically violating the Don't Repeat Yourself and the Single Point of Truth principles (if you did MVVM in C#, think about it: how often did you implement the
INotifyPropertyChanged
interface?). A solution with multiple class inheritance would be much cleaner in my opinion. In C++, the above example would compile just fine.Uncle Bob wrote an interesting article about this, that is where I got the example from. But this problem often applies to all interfaces that are *able (e.g. comparable, equatable, enumerable, etc.): a multiple class inheritance version is often cleaner in these cases, as stated by Bertrand Meyer in his book "Object-Oriented Software Construction".