Advanced JavaScript Design Patterns
Tags: showdev, javascript, react, design
Published: 2021-11-24 06:03:57



![](https://cdn-images-1.medium.com/max/2560/1*Yk1WFP5PSBOEhATlSk1GFw.jpeg)

## Overview
>  I have covered here 20+ design patterns explanations in javascript. We will be discussing all these design patterns using Javascript es6 classes.

## **About Me**

I am a react.js developer at [DhiWise](https://www.dhiwise.com/?utm_campaign=Ravi%20Sojitra&utm_source=Infl), which is a ProCode platform that helps you build clean, scalable, and customizable Node.js(Open-source), Android(Kotlin), iOS, Laravel, Flutter and React code. Focus on what matters as a programmer and let [DhiWise ]()do the rest.
https://www.dhiwise.com/?utm_campaign=Dev.to&utm_source=Dev.to
Also, If you wish to learn 
- Advanced react component patterns, [please find it here.](https://medium.com/dhiwise/react-component-patterns-805a60b88dba)
- Advanced React Roadmap, [please find it here.](https://medium.com/dhiwise/advanced-roadmap-for-react-js-developers-3a40ce4174b9)

## 🚀 What are Design Patterns?

Design Patterns are the solutions to commonly occurring problems in software design. These patterns are easily re-usable and are expressive.

According to Wikipedia
>  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.

### Types of Design Patterns

* Creational

* Structural

* Behavioral

## Creational Design Patterns

Creational Design Patterns will create objects for you instead of instantiating an object directly.

According to Wikipedia
>  In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

* Factory Method

* Abstract Factory

* Builder

* Prototype

* Singleton

**Factory Method**
It defines an interface for creating a single object and lets child classes decide which class to instantiate.

According to Wikipedia:
>  In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes — rather than by calling a constructor.

### Example

Let’s take an example of a point. We have a class of points and we have to create a Cartesian point and a Polar point. We will define a Point factory that will do this work

![Javascript factory pattern](https://cdn-images-1.medium.com/max/2000/1*KGRgeJFiEx7xNorAnSrjUw.png)

Now we will create Point Factory and we will use our factory now,

![](https://cdn-images-1.medium.com/max/2000/1*-48_4nsv2CGhSYGfRvi9cg.png)

## Abstract Factory

It creates families or groups of common objects without specifying their concrete classes.

According to Wikipedia
>  The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

### Example

We will be using the example of a Drink and Drink making machine.

![](https://cdn-images-1.medium.com/max/2000/1*NvbnGgPLcLReI_X94ZBY5w.png)

Making Drink Factory

![](https://cdn-images-1.medium.com/max/2000/1*xYEHHzyxOeYTjoII1A9e2w.png)

## Builder

It constructs complex objects from simple objects.

According to Wikipedia
>  The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming.

### Example

We will be using ab example of a person class that stores a Person’s information.

![](https://cdn-images-1.medium.com/max/2000/1*QjKwshWAgjmhuFuFz0luiw.png)

Now we will create Person Builder, Person Job Builder, and Person Address Builder.

![Javascript class factory pattern](https://cdn-images-1.medium.com/max/2000/1*u-snCihmFBhoFbnSqMeyvw.png)

Now we will use our builder,

![Javascript factory pattern](https://cdn-images-1.medium.com/max/2000/1*rQaLzULJPGHM2m_mQhPV0Q.png)

## Prototype

It creates new objects from the existing objects.

According to Wikipedia
>  The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.

### Example

We will be using the example of a car.

![Object prototype class](https://cdn-images-1.medium.com/max/2000/1*1CV1aVKZt_hG_-h8t4PmQw.png)

## Singleton

It ensures that there’s only one object created for a particular class.

According to Wikipedia
>  In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system.

### Example

Creating a Singleton class,

![Javascript singleton class pattern](https://cdn-images-1.medium.com/max/2000/1*uiEANTJKRFBRhiCHuZuLYg.png)

## Structural Design Patterns

These patterns concern class and object composition. They use inheritance to compose interfaces.

According to Wikipedia
>  In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships among entities.

* Adapter

* Bridge

* Composite

* Decorator

* Facade

* Flyweight

* Proxy

## Adapter

This pattern allows classes with incompatible interfaces to work together by wrapping their own interface around existing class

According to Wikipedia
>  In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.

### Example

We are using an example of a calculator. Calculator1 is an old interface and Calculator2 is a new interface. We will be building an adapter that will wrap up the new interface and will give us results using its new methods,

![Javascript adapter pattern](https://cdn-images-1.medium.com/max/2000/1*78Bo6i_oePTMU7z0jVOS4g.png)

## Bridge

It separates the abstraction from the implementation so that the two can vary independently.

According to Wikipedia
>  Bridge is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies — abstraction and implementation — which can be developed independently of each other.

### Example

We will be creating Renderer classes for rendering multiple shapes,

![Javascript Bridge structural design pattern](https://cdn-images-1.medium.com/max/2000/1*ddyEIyKCsjYbwMhbdnJXjA.png)

## Composite

It composes objects so that they can be manipulated as single objects.

According to Wikipedia
>  The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object.

### Example

We will be using job examples,

![Composite class pattern](https://cdn-images-1.medium.com/max/2000/1*kT3gPPgM3hQSxJrmsA2jYg.png)

## Decorator

It dynamically adds or overrides the behavior of an object.

According to Wikipedia
>  The decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

### Example

We will be taking the example of color and shapes. If we have to draw a circle we will create methods and will draw a circle. If we have to draw a red circle. Now the behavior is added to an object and the Decorator pattern will help me in that.

![Javascript decorator pattern](https://cdn-images-1.medium.com/max/2000/1*VpOs0_AG4f5j_Ofzudwt8Q.png)

## Facade

It provides a simplified interface to complex code.

According to Wikipedia
>  The facade pattern (also spelled façade) is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code.

### Example

Let’s take an example of a client interacts with the computer.

![Javascript facade pattern](https://cdn-images-1.medium.com/max/2000/1*DHlLlzyZiMTcz1MTTt6DvQ.png)

## Flyweight

It reduces the memory cost of creating similar objects.

According to Wikipedia
>  A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects.

### Example

Let’s take the example of a user. Let’s have multiple users with the same name. We can save our memory by storing a name and give it a reference to the users having the same names.

![Flyweight for reducing memory in javascript](https://cdn-images-1.medium.com/max/2000/1*BUuIR-7B4gOSaYHT-_agtQ.png)

That’s how we will use this.
Now we will make memory comparsion without Flyweight and with Flyweight, by making 10k users.

![Flayweight pattern example](https://cdn-images-1.medium.com/max/2000/1*B62P7fQI79Pa8VNADuK7CQ.png)

## Proxy

By using Proxy, a class can represent the functionality of another class.

According to Wikipedia
>  The proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else.

### Example

Let’s take the example of value proxy.

![Proxy class pattern](https://cdn-images-1.medium.com/max/2000/1*STVhb9BXAWZ3t0jKaHJQ_A.png)

## Behavioral Design Patterns

Behavioral Design Patterns are specifically concerned with communication between objects.

According to Wikipedia
>  In software engineering, behavioral design patterns are design patterns that identify common communication patterns among objects. By doing so, these patterns increase flexibility in carrying out communication.

* Chain of Responsibility

* Command

* Iterator

* Mediator

* Memento

* Observer

* Visitor

* Strategy

* State

* Template Method

## Chain of Responsibility

It creates a chain of objects. Starting from a point, it stops until it finds a certain condition.

According to Wikipedia
>  In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.

### Example

We will be using an example of a game having a creature. The creature will increase its defense and attack when it reaches a certain point. It will create a chain and attack and defense will increase and decrease.

![Chain of Responsibility](https://cdn-images-1.medium.com/max/2000/1*8cm9fGDBIkdZR4jpmULXlA.png)

Increase attack,

![](https://cdn-images-1.medium.com/max/2000/1*dEjCYvcKZMrTB2dRa4LBvg.png)

Increase defense

![](https://cdn-images-1.medium.com/max/2000/1*Y6aZO0FhWellpAU69l8dBw.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*9Ki9KTtYnoHq2b4klj0sgQ.png)

## Command

It creates objects which encapsulate actions in objects.

According to Wikipedia
>  In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

### Example

We will be taking a simple example of a bank account in which we give a command if we have to deposit or withdraw a certain amount of money.

![](https://cdn-images-1.medium.com/max/2000/1*AMX7jFmRU8pfSWahIna0nw.png)

Creating our commands,

![](https://cdn-images-1.medium.com/max/2000/1*d9DB5jurww1gHAeWTqPA3A.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*hAkHDT-vCVQQ3qehtzlblw.png)

## Iterator

Iterator accesses the elements of an object without exposing its underlying representation.

According to Wikipedia
>  In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements.

### Example

We will be taking an example of an array in which we print the values of an array and then by using an iterator we print its value backwords.

![](https://cdn-images-1.medium.com/max/2000/1*sPEIzN3bG5Tu_7mZBSw7zg.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*LZ52nqI4yECLDHXbA98Qfw.png)

## Mediator

The mediator pattern adds a third-party object to control the interaction between two objects. It allows loose coupling between classes by being the only class that has detailed knowledge of their methods.

According to Wikipedia
>  The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior. In object-oriented programming, programs often consist of many classes.

### Example

We will be using an example of a person using a chat room. Here, a chatroom acts as a mediator between two people communicating.

![](https://cdn-images-1.medium.com/max/2000/1*Q--ZXvEwOCT17AJtCjiucg.png)

Creating chat room,

![](https://cdn-images-1.medium.com/max/2000/1*K0NUHUqM4qwM1YAJ_kB0FQ.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*zc79g7X0CVnZ65mx7latQw.png)

## Memento

Memento restores an object to its previous state.

According to Wikipedia
>  The memento pattern is a software design pattern that provides the ability to restore an object to its previous state. The memento pattern is implemented with three objects: the originator, a caretaker and a memento.

### Example

We will be taking an example of a bank account in which we store our previous state and will have the functionality of undoing.

![](https://cdn-images-1.medium.com/max/2000/1*-CMBPsWAYSJPpL2EMbEF0g.png)

## Observer

It allows a number of observer objects to see an event.

According to Wikipedia
>  The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

### Example

We will be taking an example of a person in which if a person falls ill, it will display a notification.

![](https://cdn-images-1.medium.com/max/2000/1*kBDW9662fuqeqO-YuQb--A.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*BRV5QPo1YTtJ5BEa5xc1Xw.png)

## Visitor

It adds operations to objects without having to modify them.

According to Wikipedia
>  The visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.

### Example

We will be taking an example of NumberExpression in which it gives us the result of the given expression.

![](https://cdn-images-1.medium.com/max/2000/1*Bou9I22pEs7VEVQ8_vW94Q.png)

## Strategy

It allows one of the algorithms to be selected in certain situations.

According to Wikipedia
>  The strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

### Example

We will take an example in which we have a text processor that will display data based on strategy(HTML or Markdown).

![](https://cdn-images-1.medium.com/max/2000/1*srPMULYDx_SYqskVw7hF1A.png)

Creating TextProcessor class,

![](https://cdn-images-1.medium.com/max/2000/1*XVD1CNa-ucE11CqOKwyp7A.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*Gd-EIrVZpdFEJyYkOPidSQ.png)

## State

It alters the behavior of an object when its internal state changes.

According to Wikipedia
>  The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines.

### Example

We will be taking an example of a light switch in which if we turn on or off the switch, its state changes.

![](https://cdn-images-1.medium.com/max/2000/1*d7Jq--ZVu5VQ3tSrCNaLBA.png)

Let’s create a Switch class to use these On/Off state

![](https://cdn-images-1.medium.com/max/2000/1*PyT5K_SzCOdUh7y6bGRhrA.png)

## Template Method

It defines the skeleton of an algorithm as an abstract class, that how should it be performed.

According to Wikipedia
>  Template Method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps.

### Example

We will be taking an example of a chess game,

![](https://cdn-images-1.medium.com/max/2000/1*3hmYhXppUvKE0hBd3ocW1Q.png)

Creating our chess class,

![](https://cdn-images-1.medium.com/max/2000/1*iAINr2tOntV_p7Ax9y0Anw.png)

That’s how we will use this,

![](https://cdn-images-1.medium.com/max/2000/1*IWizizeeXuw2zPraRIlZXg.png)

## Overview

As we have seen all these patterns are widely used all over big organizations. Hope you might find it useful in your own adventurous project.

## Reference

[Design Patterns in JavaScript](https://www.udemy.com/course/design-patterns-javascript/) on [Udemy](https://www.udemy.com/) by Dmitri Nesteruk.

- By Ravi Sojitra
(Tech Lead | DhiWise)