Factory pattern, Avoid same switch case for different interface

时间:2018-06-19 11:15:08

标签: c# design-patterns interface factory-pattern

I have a Model which Implements 3 different interfaces

public class CustomerRateSettingModel :  IBaseFactory, IHandleSearch, IHandleSearchAggregate

I am very new with implementing design patterns and trying to implement Factory pattern to create instances. But I am unable to find a proper way to avoid the identical Switch statements while writing Factory

  public static IHandleSearch GetClassInstanceForSearch(string className)
    {
        switch (className.ToLower())
        {
            case "customerratesettingmodel":
                return new CustomerRateSettingModel();

            default: return null;
        }
    }

    private static IBaseFactory ManufactureModel(string className)
    {
        switch (className.ToLower())
        {
            case "customerratesettingmodel":
                return new CustomerRateSettingModel();

            default: return null;
        }
    }

Is there is any right way to handle scenarios like that?

For Reference : the code calling the factory

  IHandleSearch instance = ModelFactory.GetClassInstanceForSearch(modelName);


 var modelResult = instance.GetSearch(indexName, searchHistory.SearchParameters);

1 个答案:

答案 0 :(得分:4)

使用Dictionary<string,Func<object>>将名称映射到对象制造者。使用as运算符来测试object是否符合所需的接口:

static readonly IDictionary<string,Func<object>> Makers = new Dictionary<string,Func<object>> {
    ["customerratesettingmodel"] = () => new CustomerRateSettingModel()
};
public static IHandleSearch GetClassInstanceForSearch(string className) {
    return Construct<IHandleSearch>(className);
}
public static IBaseFactory GetClassInstanceForSearch(string className) {
    return Construct<IBaseFactory>(className);
}
private static T Construct<T>(string className) where T : class {
    if (!Makers.TryGetValue(className.ToLower(), out var makeObject) {
        return null;
    }
    return makeObject() as T;
}