On Wiki page for Factory method
pattern, there is following example:
public interface IPerson
{
string GetName();
}
public class Villager : IPerson
{
public string GetName()
{
return "Village Person";
}
}
public class CityPerson : IPerson
{
public string GetName()
{
return "City Person";
}
}
public enum PersonType
{
Rural,
Urban
}
public class Factory
{
public IPerson GetPerson(PersonType type)
{
switch (type)
{
case PersonType.Rural:
return new Villager();
case PersonType.Urban:
return new CityPerson();
default:
throw new NotSupportedException();
}
}
}
Here we are switching on the PersonType
to determine which object to instantiate. I know that it makes sense to use Factory method
pattern to decouple the creation of an object out of multiple objects of same type but the above code does not satisy the open-closed
principle. Whenever there is new type of IPerson
we will have to make changes to the implementation of the Factory
and if we consider future, overtime this factory method can grow pretty big.
Another pretty common example for Factory
pattern is instantiation of database where you can choose among different database servers. In this case we can have a config file and specify which database to instantiate and we are kind of creating only one object out of multiple choices. In the above case for IPerson
we are instantiating multiple object of multiple choices. Is Factory
pattern a correct choice or am I thinking too much?