This pattern consists of wrapping up constructors of different types of objects on a function and expose one generic method to return instances of these objects. This pattern is commonly used in JavaSript to create instances of very complex objects or to create large numbers of similar objects.
For example, I am going to show you design the code in a hypothetical case where I will be creating instances of objects from the concept of Media items, such as an image or a video using a factory approach.
Using require, I will be able to load modules in an easy way, thus keeping things clear enough to make a compressive code by splitting it up in modules.
Assuming that I have created this structure.
Let’s see the content for the image.js and the video.js files.
Image.js
video.js
In these files I have simply created a constructor for each of those objects, passing a parameter to set up their properties, the anonymous functions as it is, returns the object to be reachable.
Now I am going to show you the most important file here, the mediaFactory.js, which is the one that will give us a simple and reusable way to create the instances of them.
The anonymous define function receives the “
require” value to use it inside itself, the media object exposes the two types of object, I have got access to them using require to import them as modules in this file. Now what?.
This anonymous function can be used as a closure, the concept of closure basically refers to wrapping up code with a function, so the values inside it can be only acceded inside there and not globally, the function commonly returns only the variables it wants to expose on the external context. We can say that is has to do with the scope concept.
In line 9, I defined what I want to be returned, the “
createMedia” variable is a function that receives two parameters, the first one defines the type of the object we’re going to instantiate, which have to match with one of the key values in the media object created above. The “
attributes parameter” is passed in the construction of the new object which is what we’ll really return.
I have already created a structure following the factory design pattern, now all I have to do is use it. Let’s go to that file.
Init.js
This way we can easily create instances of the two types of objects by using the createMedia method, notice that in line 2 the variable “mediaFactory” is set up, and again require is used to include the module.
Init.js is like the client that consume the mediaFactory, you can see that it creates the instances of the object, but it is not really involved in the actual creation. This makes it very easy to add a new object in the future, even though I only have two types of media objects in this example, the benefits would become clearer as we add more and more different types of new media objects.