My program have two classes; both derive from same base class.
class A : MyBase
{
public A(InitVal initVal)
}
class B : MyBase
{
public B(InitVal initVal)
}
InitVal
is another class which is injected through constructor. This class is for internal usage; so I do not want to allow user to create instance of class A
and B
directly. Instead, I created method which creates these objects.
class Initiator
{
InitVal initVal;
public T CreateObject<T>(ObjectInstance objectInstance) where T : MyBase
{
MyBase myBase = null;
switch(objectInstance)
{
case ObjectInstance.A:
myBase = new A(initVal);
break;
case ObjectInstance.B:
myBase = new B(initVal);
break;
}
return (T)myBase;
}
}
ObjectInstance
is enum in above code.
This works without problem but I am sure you have never seen such ugly code earlier.
Please suggest creational pattern I should use. I want to remove ObjectInstance
enum without changing functionality. It will cleanup much.
I tried Creational Patterns mentioned on dotfactory. Factory Method
and Abstract Factory
does not look proper in this case.
My code even though look ugly, it is very simple to read and understand. I tried implementing patterns mentioned above which increases code complexity. So this is also my criteria while choosing answer.
I cannot change anything in code except Initiator
class. All other classes are not accessible to me for edit.
Aucun commentaire:
Enregistrer un commentaire