Multiple Inheritance: What's a good example?

后端 未结 2 1938
無奈伤痛
無奈伤痛 2020-12-31 11:04

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

相关标签:
2条回答
  • 2020-12-31 11:56

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

    0 讨论(0)
  • 2020-12-31 12:08

    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.

    0 讨论(0)
提交回复
热议问题