[我经常在部署策略模式时陷入分支,有没有办法使它比下面的代码更整洁:
private static TestEdition GetCurrentEdition(userconfig config)
{
if (config.Edition == Edition.typea)
{
return new TestEdition3(config);
}
else if (config.Edition == Edition.typeb)
{
return new TestEdition4(config);
}
return new UnsupportedEdition(config);
}
我倾向于经常使用这种东西:
private static Dictionary<Edition, Func<userconfig, TestEdition>> _factories =
new Dictionary<Edition, Func<userconfig, TestEdition>>()
{
{ Edition.typea, c => new TestEdition3(c) },
{ Edition.typeb, c => new TestEdition4(c) },
}
private static TestEdition GetCurrentEdition(userconfig config)
{
if (_factories.ContainsKey(config.Edition))
{
return _factories[config.Edition](config);
}
return new UnsupportedEdition(config);
}
[最大的优点是您可以在运行时配置和扩展Dictionary<Edition, Func<userconfig, TestEdition>>
。