Explaining the factory design pattern with code examples
When I was studying Computer Science, I remember my professor trying to explain factories so enthusiastically about the subject that I honestly felt bad for not fully understanding it at the time.
To be honest, I understood the concept, but the UML diagram didn't quite relate to how I could use it to create better code, and now, years later, I finally have the same enthusiasm about the topic that my professor had. Because nowadays I find myself needing to create factories from time to time.
The factory is a design pattern listed by the famous GOF design pattern book. the factory is a creation pattern that informs ways to abstract object instantiations in a way that reduces couple and make the code simple
Factories are very common and work as a base to many other patterns.
Let's create some simple examples to show the pattern. These examples are created using typescript but can be translated into any language.
In this first example, we use a factory to abstract all the logic to create a controller. This means that whoever uses the controller doesn't need to know anything about how the object is being created and its dependencies.
This abstraction means that eventually, we can change the steps of creating an object without changing everywhere the object is being used.
Now let's create a more complex example.
In this example, we create a factory that can decide which object needs to be created depending on the strategy passed. The factory will always return a Message, but depending on the type, this message can behave completely differently from one to another, which is the principle of the strategy pattern by the way.
So, all in all, the factory pattern is one of the most common patterns when working with object-oriented programming, and the goal is to abstract all the logic needed to instantiate an object. Creating a simple interface to interact with and allowing you to select the right object that needs to be used.