Design pattern to use instead of multiple inheritance

Posted by mizipzor on Stack Overflow See other posts from Stack Overflow or by mizipzor
Published on 2010-03-25T13:30:22Z Indexed on 2010/03/25 13:33 UTC
Read the original article Hit count: 388

Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can only inherit one baseclass but implement any number of interfaces (did I get the terminology right?).

For example, lets consider two classes that implement a common interface but different (yet required) baseclasses:

public class TypeA : CustomButtonUserControl, IMagician
{
    public void DoMagic()
    {
        // ...
    }
}

public class TypeB : CustomTextUserControl, IMagician
{
    public void DoMagic()
    {
        // ...
    }
}

Both classes are UserControls so I cant substitute the base class. Both needs to implement the DoMagic function. My problem now is that both implementations of the function are identical. And I hate copy-and-paste code.

The (possible) solutions:

  1. I naturally want TypeA and TypeB to share a common baseclass, where I can write that identical function definition just once. However, due to having the limit of just one baseclass, I cant find a place along the hierarchy where it fits.
  2. One could also try to implement a sort of composite pattern. Putting the DoMagic function in a separate helper class, but the function here needs (and modifies) quite a lot of internal variables/fields. Sending them all as (reference) parameters would just look bad.
  3. My gut tells me that the adapter pattern could have a place here, some class to convert between the two when necessery. But it also feels hacky.

I tagged this with language-agnostic since it applies to all languages that use this one-baseclass-many-interfaces approach.

Also, please point out if I seem to have misunderstood any of the patterns I named.

In C++ I would just make a class with the private fields, that function implementation and put it in the inheritance list. Whats the proper approach in C#/Java and the like?

© Stack Overflow or respective owner

Related posts about language-agnostic

Related posts about design-patterns