Search code examples
design-patternsfactory-pattern

Should a factory pattern be used to set state or type only


Factory creating only correct type

So here is an example of a Factory only returning the correct type:

public class BirdFactory
{
    public static IBird CreateBird(string birdType)
    {
        switch (birdType)
        {
            case "Eagle":
                return new Eagle();
            case "Penguin":
                return new Penguin();
        }
    }
}

Used like:

IBird bird = BirdFactory.CreateBird("eagle");
bird.FlyToLocation(new Location("London"));

Factoring creating correct type and setting state

Here is an example of a factory being used to set state and type:

public class BirdFactory
{
    public static IBird CreateBird(string birdType, Location locationToFlyTo)
    {
        switch (birdType)
        {
            case "Eagle":
                return new Eagle(locationToFlyTo);
            case "Penguin":
                return new Penguin(locationToFlyTo);
        }
    }
}

Used like:

IBird bird = BirdFactory.CreateBird("eagle", new Location("London"));
bird.FlyToLocation();

The question

How acceptable is the second practice? Which is more maintainable?


Solution

  • There is no cardinal rule that you cannot set state along with type in a factory pattern. And indeed combining patterns is an acceptable practice. So if you are pretty sure that the second method fits your needs perfectly, go for it.

    I preffer method 1 over method two becuase it is less ambiguous.

    IBird bird = BirdFactory.CreateBird("eagle", new Location("London"));
    

    may lead a reader to think that the eagles "lives"(or was born) in London.

    The next line:

    bird.FlyToLocation();
    

    will perplex them: "where is it flying to? Oh! You mean the bird has to fly to London?"

    bird.FlyToLocation(new Location("London"));
    

    avoids this ambiguity.