Replacing inheritance with composition in generic classes?
I've been reading a lot about composition and trying to figure how I can refactor my inheritance tree using composition. Currently a simplified version of my class looks like this:
public abstract class BaseClass
{
public abstract string displayText { get; }
public abstract List<Parameter> parameters { get; }
public abstract void FireEvent();
}
public abstract class SubClass<T> : BaseClass
{
private string _displayText;
public override string displayText { get { return _displayText; } }
private List<Parameter> _parameters;
public override List<Parameter> parameters { get { return _parameters; } }
private T _value; // ADDED TO SUBCLASS
public abstract Event<T> Evt { get; } // ADDED TO SUBCLASS
public override void FireEvent()
{
Evt.Raise(_value);
}
}
public class IntClass : SubClass<int>{}
public class StringClass : SubClass<string>{} // more subclasses like this
From my understanding, there is both inheritance and composition going on here.
SubClass<T>
Has-A: (Composition)
- List of `
Parameters
` - Field for `
Event
` - Behaviour of `
Event<T>
` which is called within it's own `FireEvent
` method
SubClass
Is-A: BaseClass
(Inheritance)
IntClass/StringClass
Is-A: SubClass<int>
& BaseClass
The reason for creating `BaseClass
` is because I need polymorphic lists. This way I can create a `List<BaseClass>
` and call `FireEvent()
` on each element in the list and access the `displayText
` and `List<Parameter>
` in a loop.
In the future I will need to add new behaviors. IntClass
may only need some of them. StringClass
may need a different set. Other variants might crop up.
How would I replace my current structure entirely with a composition based approach? Is it even doable?