1

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

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

1 回答 1

3

我经常使用这种东西:

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>>在运行时配置和扩展。

于 2020-03-27T05:56:43.450 回答