Search code examples
c#interfacemultiple-inheritanceabstraction

Multiple inheritance using interaces


Please consider the attached figure.

What I want is that the (technical-) "User" can use methods from class A, B or C by an instantiate of "HeadClass". What I try to avoid is, that I have to add a separate function for each method defined in Class A, B and C to call them through the "HeadClass". I tried to describe this in an other stackoverflow-request yesterday but have deleted it because it seemed to be unclear what I wanted to achieve. So here is an other approach.

Usually this would be achieved by inheritance (if only one class would be inherited from). But, as they told me in that deleted post, I should use Interface instead. Now, so far I thought that I know how interface work (using almost for every class), but I can't figure how I achieve this describe problem.

How would I have to fill the "???" in "HeadClass"? I am happy for any input. Thx in adavnce!

The Problem

class User
{
    public User(IHeadClass headObj)
    {
        _headObj = headObj
    }

    public DoStuff()
    {
        _headObj.Method_1
        _headObj.Method_2
        _headObj.HeadMethod
    }
    
    
}


public class HeadClass : IHeadClass, ???
{
    ???

    public HeadClass( ??? )
    {
        ???
    }

    void HeadMethod()
    {
        ... do head stuff
    }
}


public class Class_A : IClass_A
{
    public void Method_1 () { }
}


public class Class_B : IClass_B
{
    public void Method_2 () { }     
    public void Method_3 () { }
}

public class Class_C : IClass_C
{
    public void Method_4 () { }
}

I have check out this describing how to use interfaces instead. But this doesn't solve the above problem.


Solution

  • If I understand correctly you can use composition here. Something like this:

    public interface IClass_A
    {
        void Method_1 ();
    }
    
    public interface IClass_B
    {
        void Method_2 ();
        void Method_3 ();
    }
    
    public interface IClass_C
    {
        void Method_4 ();
    }
    
    
    public interface IHeadClass : IClass_A, IClass_B, IClass_C
    {
        void HeadMethod();
    }
    
    public class HeadClass : IHeadClass
    {
        private readonly IClass_A _a;
        private readonly IClass_B _b;
        private readonly IClass_C _c;
    
        public HeadClass(IClass_A a, IClass_B b, IClass_C c)
        {
            _a = a;
            _b = b;
            _c = c;
        }
    
        void HeadMethod()
        {
            ... do head stuff
        }
    
        public void Method_1() => _a.Method_1();
    
        public void Method_2() =>  _b.Method_2();
        public void Method_3() =>  _b.Method_3();
    
        public void Method_4() => _c.Method_4();
    }