Learn about Singleton & Factory Pattern Design in JavaScript

0
1965
Learn-about-Singleton-Pattern-&-Factory-Pattern-Design-in-JavaScript

Learn-about-Singleton-Pattern-&-Factory-Pattern-Design-in-JavaScript

In this tutorial we’re going to learn about two design patters: The Singleton and the Factory Pattern. The singleton is a design pattern in JavaScript which is used when we know we have only one object to be created of a specific type.

We’ll start our demonstration by creating an object character for a game. We’ll firs check if the Dwarf object already exists with typeof.

If the Dwarf object already exists, our if statement would yield true and then we’d return the Dwarf object. Otherwise, we have to create the first Dwarf object.

Let test out our new singleton.

We’re going to verify that this works by creating another dwarf:

If we run this, we can see that the name stays danny (output ‘the dwarf is danny’). So we can only create on Dwarf type, and that’s a rough overview of how the singleton pattern works.

Lets move on to factory patterns. A factory pattern can be used to generate different objects, on request.  Lets stick with our game analogy and say we want to generate weapons for the different characters, and they each will have a description that would be passed on as a parameter.

now, lets create a weapons factory that would generate specific types of weapons on demand.

The ‘class’ variable is actually an object.

In the last statement, we are defining a new weapon object for the user and passing in the description. So we are dynamically defining what type of weapon object we’re creating, and passing in the description. Now lets create an instance of the weapon factory:

We will now create a new weapon object using the factory object, to which we will pass in the description as parameter:

now lets print out some information about our weapon:

1

So  in this tutorial, we’ve seen a way to use factory pattern to dynamically create objects inside JS. We’ve made a distinction between the singleton which is a  JS design pattern used when we know we have only one object to be created of a specific type and a factory pattern which is used when we plan to generate several different objects of the same type.

LEAVE A REPLY

Please enter your comment!
Please enter your name here