Multiple Inheritance: What's a good example?

2019-02-06 15:23发布

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++.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-06 16:02

The following is a classic:

class Animal {
 public:
  virtual void eat();
};

class Mammal : public Animal {
 public:
  virtual void breathe();
};

class WingedAnimal : public Animal {
 public:
  virtual void flap();
};

// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};

Source: wiki.

查看更多
贼婆χ
3楼-- · 2019-02-06 16:14

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#:

public abstract class Observable
{
    private readonly List<IObserver> _observers = new List<IObserver>();

    // Objects that want to be notified when something changes in
    // the observable can call this method
    public void Subscribe(IObserver observer)
    {
        _observers.Add(observer);
    }

    // Subclasses can call this method when something changes
    // to notify all observers
    protected void Notify()
    {
        foreach (var observer in _observers)
            observer.Notify();
    }
}

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:

public class ImportantBaseClass { /* Members */ }

public class MyObservableSubclass : ImportantBaseClass, Observable { /* Members */ }

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".

查看更多
登录 后发表回答