I have read about a factory pattern and I wonder if it is compatible with the Open-Closed Solid Principle. In many examples a factory method takes enum and then in the switch statement creates a concrete object, please see C# example on the wiki page. It sounds reasonable that I might want to decide which object should be created based on enum. On the other hand when enum is extended I also have to add a new case in the switch statement which breaks Open-Closed Solid Principle.
I also wonder if the wiki page really describes a factory method pattern or something which is called a simple facttory. I can create the following interface:
public interface IPersonFactory
{
IPerson CreatePerson();
}
and then implement a concrete factory, for example:
public class VillagerFactory : IPersonFactory
{
public IPerson CreatePerson()
{
return new Villager();
}
}
Then based on enum I can decide which factory implementation should be used but again when enum is extended I also have to add a case in the switch statment somewhere in the code so I'm not sure if the second approach is better.
Could you please clarify it ?
Aucun commentaire:
Enregistrer un commentaire