Does the Factory Pattern Violate the Open/Closed Principle?

designdesign-patternsfactoryfactory-method

Why does this ShapeFactory use conditional statements to determine what object to instantiate. Dont we have to modify ShapeFactory if we want to add other classes in the future? Why doesnt this violate the open closed principle?

Factory Pattern Design

ShapeFactory Design

Best Answer

The conventional object-oriented wisdom is to avoid if statements and replace them with dynamic dispatch of overridden methods in subclasses of an abstract class. So far, so good.

But the point of the factory pattern is to relieve you from having to know about the individual subclasses and work only with the abstract superclass. The idea is that the factory knows better than you which specific class to instantiate, and you will be better off working only with the methods publishd by the super class. This is often true and a valuable pattern.

Therefore, there is no way that writing a factory class can forego the if statements. It would shift the burden of choosing a specific class to the caller, which is exactly what the pattern is supposed to avoid. Not all principles are absolute (in fact, no principle is absolute), and if you use this pattern you'd assume that the benefit from it is greater than the benefit of not using an if.