使用静态工厂模式时如何避免分支?

How to avoid branching while using a static factory pattern?

我在部署静态工厂模式时经常卡在分支中,有没有办法让它比下面的代码更整洁:

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