我有一个工厂方法,如下所示。有没有更好的方法来设计这个,所以我不必使用switch语句并实现开放封闭原则
public IPolicy CreatePolicy(Context context)
{
IPolicy policy = default(IPolicy);
ISettings settings = _settings.Get(context);
Policy policyType = (Policy) Enum.Parse(typeof(Policy), settings.Policy);
switch (policyType)
{
case Policy.Policy1:
policy = new Policy1(_policy1Service, _logHandler);
break;
case Policy.Policy2:
policy = new Policy2(_policy2Service, _logHandler);
break;
case Policy.Policy3:
policy = new Policy3(_policy1Service, _policy2Service, _logHandler);
break;
}
return policy;
}
答案 0 :(得分:0)
假设枚举文字与您的类名完全相同,您可以根据枚举文字动态创建实例,如
public static IPolicy CreatePolicy(Policy policy)
{
//Change this if the namespace of your classes differs
string ns = typeof(Policy).Namespace;
string typeName = ns + "." + policy.ToString();
return (IPolicy)Activator.CreateInstance(Type.GetType(typeName));
}
只需像
那样添加构造函数参数即可return (IPolicy)Activator.CreateInstance(Type.GetType(typeName),
_policy1Service, _logHandler);
由于这是非常不寻常的,请考虑向IPolicy
添加Initialize(...)方法以传递这些参数以允许空构造。