简体   繁体   中英

How to avoid branching while using a static factory pattern?

I often get stuck in branching when deploying the static factory pattern , is there a way to make it more neat than the below code :

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

I tend to use this kind of thing a lot:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM