Search code examples
c#ooprefactoringstatic-factory

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

Solution

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