I was recently asked if the factory method design pattern was a violation of the open-closed principle.
When you are adding a new subtype, you have to modify the factory method to enable to return additional subtypes. Also, you might be creating a new subtype for the factory method to return. Isn’t it an indication that you are violating the open-closed principles if you have to change multiple to files to enable a single new behavior?
The open-closed principle states that entities (modules, classes, functions, etc.) should be open to extension and closed to modification. The factory method design pattern is a creational pattern that allows us to instantiate the proper type without specifying the exact implementation of that type.
Consider the following:
- The behavior of the factory method remains the same when you add the ability to return a new subtype; none of the callers of the factory method are forced to change
- A new subtype that is created to be returned by the factory method is an addition by extending or implementing a type (hence, subtype), not a modification
If no behaviors have been changed, and all new functionality is an extension of existing functionality (or completely new functionality), we are complying with the open-closed principle.