Keshav Raghav
Keshav Raghav

Reputation: 347

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

Upvotes: 0

Views: 129

Answers (1)

Enigmativity
Enigmativity

Reputation: 117144

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.

Upvotes: 2

Related Questions