'Object initialization strategy for related objects
The scenario I'm working is the next: There's a Base (non-abstract) class that has several classes that inherit from it. Based on a type I have to create one or another, my initial code is like this:
switch (type)
{
case BaseType.Standard:
_list.Add(Standard.Create(<params>)));
break;
case BaseType.Special:
_list.Add(Special.Create(<params>));
break;
}
Switch statement was simplified. Each specialization of the base class, has it's own initialization params, meaning that the client class is having a lot of params to cover for all the possible params to initialize each object from the child classes (or the base class itself). I was wondering if someone could help me to figure a better way of initializing each of the classes (both childs and base). I was thinking in something like Abstract Factory design pattern, but I'm not so sure if it fits my use case.
I don't want to start having a huge switch statement per each type I need to initialize nor a method with a huge parameter list.
Minimal reproducible scenario:
public class Client
{
public Client(int clientProperty)
{
ClientProperty = clientProperty;
}
public int ClientProperty { get; set; }
public IEnumerable<BaseType> BaseTypes { get; set; } = new List<BaseType>();
public BaseType CreateBase(BaseTypeEnum type, string paramA, int paramB, int paramC, string paramD, string paramE, int paramF)
{
switch (type)
{
case BaseTypeEnum.Base:
return new BaseType(paramA);
case BaseTypeEnum.Colored:
return new ColoredBaseType(paramA, paramB, paramC);
case BaseTypeEnum.Special:
return new SpecialBaseType(paramA, paramD, paramE, paramF);
default:
return new BaseType(paramA);
}
}
}
public enum BaseTypeEnum
{
Base,
Colored,
Special
}
public class ColoredBaseType : BaseType
{
public ColoredBaseType(string paramA, int paramB, int paramC)
: base(paramA)
{
ParamB = paramB;
ParamC = paramC;
}
public int ParamB { get; set; }
public int ParamC { get; set; }
}
public class SpecialBaseType : BaseType
{
public SpecialBaseType(string paramA, string paramD, string paramE, int paramF) : base(paramA)
{
ParamD = paramD;
ParamE = paramE;
ParamF = paramF;
}
public string ParamD { get; set; }
public string ParamE { get; set; }
public int ParamF { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
