简体   繁体   中英

Abstract Factory or Factory Method for types with different constructor arguments

I have a factory method as given below. Is there a better way to design this so I do not have to use switch statement and achieve open closed principle

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;
}

Supposed the enum literals are exactly the same as your class names, you could dynamically create the instances based on the enum literal like

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));
}

Passing constructor parameters is also possible by simply adding them like

return (IPolicy)Activator.CreateInstance(Type.GetType(typeName),
    _policy1Service, _logHandler);

Since this is very unusual, think about adding an Initialize(...) method to IPolicy to pass these parameters to allow an empty constuctor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM