Design Patterns in javascript in a nutshell

Lalit Kushwah
3 min readAug 21, 2022

--

Hello readers, in this blog I’ll share my knowledge about the design patterns that are being used in javascript projects. These patterns are widely used and accepted in the IT industry and don’t bound by the technology stack. I’ll try to explain these patterns with coding examples so that it would be easy for you to understand and co-relate them to your day-to-day development.

To absorb the shared knowledge at its fullest you must have a good understanding of javascript

Mediator/Middleware Pattern

The mediator pattern makes it possible for components to interact with each other through a central point: the mediator. Instead of directly talking to each other, the mediator receives the requests, and sends them forward! In JavaScript, the mediator is often nothing more than an object literal or a function.

Singleton Pattern

You should implement this pattern to the scenarios where you want to restrict the consumers by not letting them create another instance of a class (classes in javascript are the syntactic sugar to the functions). By doing this you are enforcing consumers to use a single copy of the created object. On another way round you want to share the properties amongst the consumers and provide them the privilege to change/access the properties based on their operation.
In javascript, an object is of reference type which can be used to implement this feature.

Proxy Pattern

This pattern helps you to create a layer of interaction while accessing/manipulating objects by creating a proxy object from the original one. “A proxy means a stand-in for someone else. Instead of speaking to that person directly, you’ll speak to the proxy person who will represent the person you were trying to reach”. This mechanism helps to apply a hook where you have control to perform some validation prior to accessing/manipulating the properties of the object.

Prototype Pattern

Sometimes you have to create objects with similar properties, in such cases instead of repeating the properties for all the objects you can leverage the “prototype pattern” by creating a single class containing all the common properties and inheriting the properties while creating a new object out of it.

Mixin Pattern

A mixin is an object that we can use in order to add reusable functionality to another object or class, without using inheritance.
Let's understand this with an example, create a class with basic functionality like below

Reference

  1. https://play.google.com/books/reader?id=BnJLEAAAQBAJ&pg=GBS.PT197&hl=en
  2. https://developer.mozilla.org/

--

--

Lalit Kushwah
Lalit Kushwah

Written by Lalit Kushwah

I am a full-stack developer who loves to explore, share technical and quality stuff.

No responses yet