使用策略时如何避免分支?

 收藏

部署策略模式时,我经常卡在分支中,有什么方法可以使它比下面的代码更简洁:

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

    The huge advantage is that you can configure and extend the Dictionary<Edition, Func<userconfig, TestEdition>> at run-time.