4 Design patterns in JavaScript every JavaScript developer should know

Okay.!! If we will search across the internet to find the design pattern, which will be suitable for the specific use case we are in to, then I feel it is pretty hard to find the exact match, unless we have a better understanding of the design patterns.

So what is design patterns?

If we will see a Wikipedia for the exact definition then the design pattern is: In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

In javascript there are majorly 4 design patterns used by the software companies.

  1. Singleton pattern
  2. Modular pattern
  3. Prototype pattern
  4. Observer Pattern

1. Singleton Pattern:

Image result for singleton pattern javascript

Singleton pattern is mainly used when we don’t create unnecessary objects of the particular function. Let understand it from the example,

We have a printer in the house, we need to create a program which will be responsible to start the printer, and if the work of the printer is done then stop it, in that let suppose we have 3 computers connected to it, so according to the example given below.

function printer() {
  var isRunning = false;
  return {
    start: function () {
      if (isRunning) {
        console.log('Started already')
      } else {
        isRunning = true;
        console.log('Starting printer')
      }
    },
    stop: function () {
      if (isRunning) {
        isRunning = false;
        console.log('Stopping printer')
      } else {

        console.log('Printer is not running.')
      }
    }
  }
}
//PC 1:  This rich guy assuming he has his own printer
var print = new printer();
print.start();
print.stop();

//PC 2: Unfortanely this guy also doing the same thing
var print = new printer();
print.start();
print.stop();

//PC 3: What happened to this guy
var print = new printer();
print.start();
print.stop();

 

In the above code since everyone is creating their own object, none of them will ever know whether the print is already processing other requests

.
So now to eliminate this kind of situation.

We need to make the printer function singleton as shown below

 

2. Modular Pattern:

Modular pattern basically wrapping up of data in a way that, some the property will be private while creating an object of the function and some of the property will be public which will be accessible through the objects as shown below:

 

 

In the above example, an instance of the function Employee object will never have a functionPrivate. Hence modular pattern where a function can decide whether to expose the particular property of the function or not, I need to expose the return it through an object.

 

3. Prototype Pattern:

Image result for prototype javascript

Before we move ahead with the Prototype Pattern first weed to understand What is a prototype?

The Prototype is, from where we inherit properties and methods from the Object. Let’s understand it through the code.

Let’s suppose we have a function Car which has properties like NumberOfWheels, Manufacturer, Make. Now properties are the one which required to make cars, now what does the cars do it Runs and Stop. These are the functionality we need to add the cars when we will done with the production.

TeslaModels = function () {
    this.numWheels = 4;
    this.manufacturer = 'Tesla';
    this.make = 'Model S';
}
// car object will have properties like <em>numWheels, manufacturer, make</em>
var car  = new TeslaModel()
console.log(car.numWheels) //4
console.log(car.manufacturer) //Tesla
console.log(car.make) //Model S

When we create properties or methods inside a function referring to this object those properties and function will be added into the prototype. Which can be accessed through the object of that particular function.

 

Now at this point, if we want to add methods to the same function we can’t do that in an ordinary way. To do this we need to add those functions through the prototype.

To understand this, the proper use case will be, let’s assume this TeslaModels function was in some other javascript file Tesla.js which cannot be edited or we don’t have permission to modify the function. In that case, what we can do is we can add those functions to the prototype [as shown below:

 

In the above example, we have added the go and stop function through the prototype to the same TeslaModel function.

 

4. Observer Pattern:

First, we will understand What is Observer Pattern?

Image result for observer design pattern

The Observer Pattern is a popular pattern used across all sorts of JavaScript applications. The instance (subject) maintains a collection of objects (observers) and notifies them all when any changes to that particular state occur. Does that making you bit confused or upset? Okay we will see a use case for the observer pattern,

According to Quora:

1.) When you subscribe to any website.

You are on the observer in this case who has subscribed to a website (Subject) for getting notified about its post.

2.) Follow feature on Quora.

As I can see right now, there are 18 followers of this question. As soon as I click on Submit after writing my answer, Quora (Subject) will send a notification to all 18 followers (observers).

3.) Cricket Display

The scoreboard display displays the average score etc information as per the current status of the match. Whenever any score changes, the scoreboard gets refreshed. So, the display board is the observer here and Subject is the panel sending the current score status to the board.

5.) Whatsapp Group

Whenever any person sends any message in the group, all the people who are in the group get notified.

 

Enough talk! Let’s see the above example from the little bit of code.

 

 

I hope the above explanation makes a little bit of sense. Queries in the comments will be appreciated.

 

Playground

 

Thank you!!