Multiple Inheritance: What's a good example?

雨燕双飞 提交于 2019-11-30 09:12:51

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!