Greetings everyone!
I'll try to make my problem simple: I have an enum
to select which ObjType
I should use (ObjTypeA
and ObjTypeB
both inherits from ObjType
). So I created a method to extend the given enum
, in order to return a new instance according to the selected property in the enum
, like follows in the code. I think it works more or less like a factory design pattern. So far so good, but eventually, like in the class MyClass
, I may attempt to create n
instances of ObjTypeA
or ObjTypeB
, but I'll have to face the if
statement everytime I call the GetObjTypeInstance()
method. So:
- Can an
enum
return an instance, something like:public enum EObjType { ObjTypeA = new ObjTypeA(), ObjTypeB = new ObjTypeB() }
? Actually, it'd be better to append someGetInstance()
method to theObjTypeA
and to theObjTypeB
options in theenum
. If there's a way to do this, how can I do it? Doing this I'd avoid those if statements every while step. - Is there any other (and better) way to this this (if you understood my problem...)? How?
Thanks in advance!
Follow the example code:
public static class EObjTypeExt
{
public static ObjType GetObjTypeInstance(this EObjType ot)
{
if (ot == EObjType.ObjTypeA)
{
return new ObjTypeA();
}
else if (ot == EObjType.ObjTypeB)
{
return new ObjTypeB();
}
throw new ArgumentOutOfRangeException("unrecognized type!");
}
}
public enum EObjType { ObjTypeA, ObjTypeB }
public class MyClass
{
ObjType[] obj { get; set; }
public MyClass(EObjType otEnum, int n)
{
this.obj = new ObjType[n];
int i = 0;
while (i < n)
{
this.obj[i] = otEnum.GetObjTypeInstance();
i++;
}
}
}