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: 391
language-agnostic
|design-patterns
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 UserControl
s 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:
- I naturally want
TypeA
andTypeB
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. - 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. - 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