JavaScript Pattern: Factory Pattern

Tram Ho

The pattern I introduced is a pattern that gives us an overview, an interface to create Objects. This pattern is called a Factory Pattern and it makes it easier to create an Object in javascript.

First, create a folder called factory .

Factory Pattern encapsulates a constructor for many types of Objects and returns an instance of the Object through a simple API. It makes it easy to create multiple Object types by calling a simple API that returns that Object type.

Let’s start creating constructors. The following functions will return a new Object of a specific type when created

In the factory folder, create a laptop.js file

We create a constructor of the Laptop. It accepts an Object parameter containing the properties of the Object to create, in this case RAM size, HDD size and the name of the laptop.

Then, we export this function as a module.

Next we create a file called tablet.js

Now we have built 2 basic constructors. Next we create a factory function to also provide an API for creating the above Objects.

Here, we will import constructors to create Laptops and Tablet, then we create an object called gadget using constructor names as keys. It gives us access to the constructors we want by using gadget [type]. Finally, we export an object from this module by declaring a createGadget function. This function accepts 2 parameters as a gadget form and its properties.

You should note that when we call a function with the keyword new in JS, we get an empty object returned with an this this bound to the processing function.

Next, we use our factory pattern API as follows:

As we saw, we created a Laptop object and a Tablet object, each of which has its own specifications. And this is called factory pattern.

Using and implementing patterns is often very simple, but what it brings is great. Pattern makes coding easier, cleaner, and helps us not to be overwhelmed by complicated problems. Perhaps at the simplest level, applying a pattern can be a bit time consuming, but when things go further and bigger, the Pattern is a great salvation.

Share the news now

Source : Viblo