I have an abstract base class with for example two subclasses. In the abstract class I use the template pattern in the "real world" but for this example lets say I have a generator method which returns the type AbstractBaseClass. Now I want the instance to be the concrete type at runtime. This is important for the template pattern as I use different implementations and hooks in each subclass.
For now I came up with the following pseudo code. I check whether this is a concrete class and call the constructor of either one of the subclasses and return the new Instance.
public abstract class AbstractBaseClass
{
private string _someString1;
private string _someString2;
protected AbstractBaseClass(string someString1, string someString2)
{
_someString1 = someString1;
_someString2 = someString2;
}
public AbstractBaseClass GenerateClass()
{
//...
if(this is SubClass1)
{
return new SubClass1("Foo1", "Foo2");
}
if(this is SubClass2)
{
return new SubClass2("Foo3", "Foo4");
}
return null;
}
// more methods
}
public class SubClass1 : AbstractBaseClass
{
public SubClass1(string someString1, string someString2) : base(someString1, someString2)
{ }
// more methods
}
public class SubClass2 : AbstractBaseClass
{
public SubClass2(string someString1, string someString2) : base(someString1, someString2)
{ }
// more methods
}
So far so good. But now I want my code to be open for extensions but closed for modifications. I want to be able to add as many subclasses as I want, but don't have to change the generator method. How can this be achieved?
So it gets decided at runtime which instance to create. Keep in mind that I don't have an empty constructor. But there is in every case a constructor with the same signature.
I found this post. It seems to go this direction but it didn't really helped me:
Thanks!