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 factory. 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 statement somewhere in the code so I'm not sure if the second approach is better.
Could you please clarify it ?
GoF’s Factory Method pattern has nothing to do with enum and in fact is very compatible with the Open-closed Principle.
Let’s say you are coding a class C. At some code inside C, you use the new keyword to create objects of some class X.
Later, you need to reuse class C somewhere, but with customization. The only needed customization is that inside C you want to create objects of some derived class of X, say X'.
Then you apply the Factory Method pattern by making the class C more abstract: add an abstract method with signature returning an object of type X, replace every call to new X by the call to the abstract method. The rest code of class C is untouched.
We call that abstract method Factory Method.
Now you can reuse the class C somewhere: write class C' inheriting C, implement the abstract method, let it create (typically with the new keyword) and return an object of whatever type X, X', X'' you want.
As you can see, the class C is open: it leaves the room for extension with the abstract method. It is closed: its source code does not need to be modified.
Developing software by adding more classes, not by (or rarely by) modifying existing classes. That’s the vision of OOP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With