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
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.
- 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 necessary. 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…