DEV Community

Cover image for A pattern a day keeps the reviewers away - [Day 5] - Abstract Factory Pattern
Antonio Djigo
Antonio Djigo

Posted on

A pattern a day keeps the reviewers away - [Day 5] - Abstract Factory Pattern

Hey 👀✨

During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now.

It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.

Because doing good code will help you, your workmates, and those who will be in the future.

Teamwork!

Do teamwork!

Today, I'll write about a famous one. It is called the Abstract Factory Pattern.

Let's say you have a magic computer generator, where you three families, Linux, macOS, and Windows. Each one has three elements of its own, a calculator, a text editor, and a terminal. For each machine that you are going to build, software on them must match with their OS in order to work. Also, you don't want to change your OS code whenever you want to add a new tool, it should always support every new tool on its own!

If you have felt before that you've suffered this, then you have to choose the Abstract Factory Pattern, where you will create an interface that can be implemented on each of the OS's tools.

A happy factory it is

In the next diagram, you'll see how an Abstract Factory diagram is defined, so you get an idea of how the idea works.

A computer factory diagram

Things you need to have in mind when working with abstract factories:

  1. Use the Abstract Factory when your code needs to work with various families of related products, but you don’t want it to depend on the concrete classes of those products.
  2. The code may become more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.

If you follow the ideas raised above, you will have an amazing abstract factory ready to mass-produce.

odly satisfying

It will be as oddly satisfying as this gif.

Now, you'll create new products with similar characteristics in a ✨ clean and efficient way ✨


And this is my fifth article about design patterns for the series "A pattern a day keeps the reviewers away".

Bye!

Wow, 5 posts. I've never expected to reach the 5 days strike

I'll try to keep posting every day one of the different patterns that are around. I can't promise I'll fulfil this task every day though!

You can read more about this pattern at:

  1. Refactoring Guru
  2. Sourcemaking

Also, you can follow me so you are tuned to whenever I post something through my Twitter account!

Top comments (0)