I’ve recently be challenged by freshly written code at my company where they used the factory pattern. This led me to research into why one would want to use it. In a lot of my research, they discourage it until it is really needed because it adds complexity with the additional classes and creation logic.
Here are some of my additional thoughts:
- This pattern hides the creation of an object.
- Useful when creating the object involves multiple steps.
- Centralizes object creation so that if it needs to change it only needs to be changed in one place.
- Useful if you have a lot of code that checks if object type is this…then do this. This really is one of the most useful features I see.
- It could be used for unit testing to switch in test data in place of live data.
- Can bring unnecessary complexity: http://www.oodesign.com/factory-pattern.html , also agile principles, patterns, and practices in c#, Robert Martin.
- Case Switch pattern is easier and more useful in that you don’t have to create a method for each and the calling logic doesn’t have to know what type of object it is dealing with.