The factory method pattern
The factory method pattern is designed to solve the following design problems:
- How to create different implementations of your objects, based on the creator class
- How to let subclasses define how to instantiate your objects
The factory method pattern lets you decouple the call site from the instantiation site in your code. This makes it easier to refactor, update, or change the instantiation of the target object without compromising the consuming part of your code.
The factory method will be responsible for instantiating objects, instead of the call site. It usually comes in multiple flavours:
- Letting subclasses define different implementations and classes
- Using parameters to define the kind of object returned by the factory
Using the factory method pattern
Let's see how we can leverage the factory method pattern in order to improve existing code.
Let's say you're building an app that let users poke, message, or call their contacts, as follows:
enum ContactAction { case...