← BackFeb 26, 2022 - 2 min read

Finally understanding the factory design pattern

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.

What are factories

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.

Code example

Let's create some simple examples to show the pattern. These examples are created using typescript but can be translated into any language.

1class ControllerFactory { 2 static create() { 3 const repo = new DatabaseConnection(); 4 const service = new Service(repo); 5 const authenticator = new Authenticator(); 6 return new Controller(service, authenticator); 7 } 8} 9

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.

1interface Message { 2 send(): void; 3} 4 5class EmailMessage implements Message { 6 send() { 7 // ... 8 } 9} 10 11class TelegramMessage implements Message { 12 send() { 13 // ... 14 } 15} 16 17class MessageFactory { 18 static create(type: 'email' | 'telegram'): Message { 19 if (type === 'email') return new EmailMessage(); 20 if (type === 'telegram') return new TelegramMessage(); 21 } 22} 23 24class Application { 25 main() { 26 const message = MessageFactory.create('email'); 27 message.send(); 28 } 29} 30

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.