AlgorithmsCodilityPatternsTutorials

A common pattern i many programming languages, factory is the means of creating objects without calling the new operator.

The advantage here is more flexibility, cleaner codebase and overall abstraction of true object creation mechanism through a clear interface.

Let’s see that on example. I’ll try to make explain it on a really simple example, and hopefully, whenever you think of a factory pattern, you will imagine a pub after this article 🙂

So, say you have a pub and want to create some beverages, first thing you are going to need is a beverage abstract class:

(the weird function arguments notation is called object destructuring, you can read more about it here). Next, lets create some drinks!

Now lets make that beverage into a factory

Allright, we got it to work, i hope by now you can see the benefits of this design. Now, lets try an even more dynamic approach. The Abstract Factory!

The abstract factory, a pub in our case, is implemented by providing the means to register the types of beverages and storing them privately using closure. This way it is possible to dynamically add factories and use them at will.

I hope that now you have a clear vision of how the factory is implemented in Javascript, and as it is pretty common, you will surely find this knowledge useful.