For what I want to achieve I ended up with some kind of generic composite pattern.
public abstract class Component
{
}
public abstract class Composite<ChildType> : Component where ChildType : Component
{
public readonly Dictionary<int, ChildType> children;
public Composite()
{
children = new Dictionary<int, ChildType>();
}
public void AddChild(ChildType child, int childPosition)
{
if (children.ContainsKey(childPosition))
{
children.Remove(childPosition);
}
children.Add(childPosition, child);
}
}
With the pattern above, I have the following deriving classes.
public class A : Composite<B>
{
}
public class B : Composite<C>
{
}
public class C : Component
{
}
Now, this ended up working very well for my purposes. Things developed and I felt the need of extracting some functionality from B into a base class and creating two subclasses from B. Let's call the base class BaseB and its subclasses B1 and B2.
I want B1 to act as if inheriting from Composite and B2 from Composite (just like the old B class). As for A, it should be able to have children of any subclass of BaseB. But naturally it wants me to provide a type argument for BaseB, so I ended up providing the type Component. Is there a way to avoid providing a type for BaseB?
//public class A : Composite<BaseB<Component>> This works
public class A : Composite<BaseB> // this doesn't work
{
}
public class BaseB<GetItFromTheSubClass> : Composite<GetItFromTheSubClass> where GetItFromTheSubClass : Component
{
}
public class B1 : BaseB<B2>
{
}
public class B2 : BaseB<C>
{
}
public class C : Component
{
}
Aucun commentaire:
Enregistrer un commentaire