工厂模式,避免不同接口使用相同的开关盒 [英] Factory pattern, Avoid same switch case for different interface
问题描述
我有一个实现3个不同接口的模型
I have a Model which Implements 3 different interfaces
public class CustomerRateSettingModel : IBaseFactory, IHandleSearch, IHandleSearchAggregate
我对实现设计模式并尝试实现Factory模式来创建实例非常陌生.但是我无法找到一种适当的方法来避免在编写Factory时使用相同的Switch语句
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);
推荐答案
制作一个 Dictionary< string,Func< object>>
以将名称映射到对象制造者.使用 as
运算符测试 object
是否符合所需的接口:
Make a Dictionary<string,Func<object>>
to map names to object makers. Use as
operator to test object
for compliance with the desired interface:
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;
}
这篇关于工厂模式,避免不同接口使用相同的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!