DEV Community

Cover image for Advanced JavaScript Design Patterns
DhiWise
DhiWise

Posted on • Edited on

Advanced JavaScript Design Patterns

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, 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

🚀 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

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

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.

Making Drink Factory

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.

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

Javascript class factory pattern

Now we will use our builder,

Javascript factory pattern

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

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

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

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

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

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

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

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

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

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

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

Increase attack,

Increase defense

That’s how we will use this,

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.

Creating our commands,

That’s how we will use this,

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.

That’s how we will use this,

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.

Creating chat room,

That’s how we will use this,

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.

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.

That’s how we will use this,

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.

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).

Creating TextProcessor class,

That’s how we will use this,

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.

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

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,

Creating our chess class,

That’s how we will use this,

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 on Udemy by Dmitri Nesteruk.

  • By Ravi Sojitra (Tech Lead | DhiWise)

Top comments (15)

Collapse
 
notiv profile image
Mike

Code in screenshots? Genius

Collapse
 
gangsthub profile image
Paul Melero

Advanced JS pro tip: don't use classes in JavaScript.

Collapse
 
sannajammeh profile image
Sanna Jammeh

NestJS has entered the chat

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

React Hooks changed the description for this group to "really, don't use classes in JavaScript" 😆

Collapse
 
prabhukadode profile image
Prabhu

Saving this as I will go through it in future.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
prabhukadode profile image
Prabhu

ha reading this again

Collapse
 
pdrmdrs profile image
Pedro Paulo Paiva de Medeiros

That was an amazing article man!

It goes straight to the point on showing those patterns. Really helpful.

Saved to use as a cheatsheet someday, haha, :D

One friendly tip I would like to give you is about those code screenshots.
Next time, try using the code formatter that the editor give you. It helps the readability (also, in mobile devices, the screenshots don't show too much detail at the large ones).

Collapse
 
daw_alberto profile image
Alberto García

Hi Ravi 👋

A post very interesting! I enjoyed reading it, but I have a little doubt
In the second design patter(Abstract Factory) you create the class DrinkFactory with the method prepare, and this method is never used why do you created it then?

Many thanks =)

Collapse
 
ravisojitra profile image
ravi

Thanks Alberto for this observation.
But it's kind of an extension of functionality if you want to use. Though i have not used it in example, but it can give you an idea that how you can customize the behaviour with base methods which can be applied to all the factories that extends base class.

Collapse
 
rakeshsinghjamwal profile image
rakeshsinghjamwal

Bookmarked for a weekend read

Collapse
 
matheuslipk profile image
MATHEUS ARAUJO DE ALCANTARA

Excellent

Collapse
 
bazeng profile image
Samuel K.M

Wow, i have saved this for later. Thanks man

Collapse
 
passtionatecoder profile image
Aqib Khan

Great ever

Collapse
 
hasnat150822 profile image
Hasnat150822

Nice but detail code is not much provided. You have just put a part of code snippet not fully code provided. I think you should provide detail code examples. However it was nice.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.