Skip to main content

Common Design Patterns In JavaScript

Updated 5 min readMarkdown
Common Design Patterns In JavaScript

Design patterns offer a shared language for organizing code, simplifying comprehension and bolstering collaboration among developers. Here are some of the most popular design patterns used in JavaScript.

The Singleton Pattern

In mathematics, a singleton, also known as a unit set, is a set with exactly one element. For example, the set {null} is a singleton.

You can implement the Singleton pattern by creating a class with a method that creates a new instance of the class only if one doesn’t already exist. If an instance already exists, it simply returns a reference to that object.

ES2015+ allows us to implement the singleton pattern to create a global instance of a JavaScript class that is instantiated once. You can expose the singleton instance through a module export.

// Instance stores a reference to the Singleton
let instance;

const randomNumber = Math.random();

// Singleton
class PhoneSingleton {
  // Get the Singleton instance if one exists
  // or create one if it doesn't
  constructor() {
    if (!instance) {
      instance = this;
    }
    return instance;
  }
  // Public methods
  getRandomNumber() {
    return randomNumber;
  }
}
// [ES2015+] Default export module, without name
export default MySingleton;

What makes the Singleton is the global access to the instance:

// Usage:
import PhoneSingleton from './PhoneSingleton';

const singleA = new PhoneSingleton();
const singleB = new PhoneSingleton();
console.log(singleA.getRandomNumber() === singleB.getRandomNumber());
// true

As an example, let’s say that you have a trivial application which is used for counting how many times buttons have been clicked.

You should keep track of the number of button presses in one object which provides:

  • the functionality of counting,

  • and providing the current number of clicks.

If that object wasn’t a singleton (and the buttons would each get their own instance) the click count wouldn’t be correct.

The Observer Pattern

The observer pattern is a software design pattern in which an object, called 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.

The nice thing is you don’t have to be the only subscriber. That’s why multiple observers can subscribe to the subject.

Since in JavaScript everything is event-driven rather than always asking if an event happened, you should let the event inform you.

// Define the subject (observable)
class Subject {
  constructor() {
    this.listeners = [];
  }

  addListener(subscriber) {
    this.listeners.push(subscriber);
  }

  removeListener(subscriber) {
    this.listeners = this.listeners.filter(item => item !== subscriber);
  }

  click() {
    this.listeners.forEach(subscriber => subscriber());
  }
}

In the next code snippet, the Subject class is the observable object that maintains a list of listeners (observers) and notifies them when its click method is called.

// Define the observer
const button = new Subject();

const showMessage = () => {
  console.log("Button clicked!");
}

const showAlert = () => {
  alert("Button clicked!");
}

// Add subscribers to the subject
button.addListener(showMessage);
button.addListener(showAlert);

// Trigger the subject's action
button.click(); 
// logs "Button clicked!" and shows an alert box

// Remove a subscriber from the subject
button.removeListener(showMessage);

// Trigger the subject's action again
button.click(); 
// shows an alert box only

The observer pattern allows to define a one-to-many relationship between objects so that when one object changes state, all its dependents are notified and updated automatically.

The Decorator Pattern

Decorators are a structural design pattern that aims to promote code reuse. We can use them to modify existing systems where we wish to add additional features to objects without heavily changing the underlying code that uses them.

Decorating Constructors with New Functionality:

// A vehicle constructor
class Vehicle {
    constructor(vehicleType) {
        // some sane defaults
        this.vehicleType = vehicleType || 'car';
        this.model = 'default';
        this.license = '00000-000';
    }
}

// Test instance for a basic vehicle
const testInstance = new Vehicle('car');
console.log(testInstance);

// Outputs:
// vehicle: car, model:default, license: 00000-000

Lets create a new instance of vehicle, to be decorated:

const truck = new Vehicle('truck');

// New functionality we're decorating vehicle with
truck.setModel = function(modelName) {
    this.model = modelName;
};

truck.setColor = function(color) {
    this.color = color;
};

// Test the value setters and value assignment works correctly
truck.setModel('CAT');
truck.setColor('blue');

console.log(truck);

// Outputs:
// vehicle:truck, model:CAT, color: blue

Here, truck is an instance of the class Vehicle, and we also decorate it with additional methods setColor and setModel.

The MVC Pattern

MVC(stands for Model-View-Controller) is an architectural design pattern that encourages improved application organization through a separation of concerns. The pattern aims to separate an application into three interconnected components:

  1. Model: represents the data and business logic of the application.

  2. View: represents the user interface and presentation layer of the application.

  3. Controller: acts as an intermediary between the model and view components. It receives input from the user and updates the model accordingly. It also updates the view based on changes in the model.

By separating the application into these three components, the MVC pattern helps developers to achieve a clean and organized codebase, with each component being responsible for a specific task.

The first among these frameworks include Backbone, Ember.js, and AngularJS. More recently, React, Angular and Vue.js ecosystems have been used to implement different variations of the MVC family of patterns.


Familiarity with these patterns enables us to recognize recurring patterns in project requirements and translate them into better reliable solutions.



About the author

  • I am a front-end developer experienced working with React and Typescript.

    So far I worked with product owners from multiple areas such as education, supply chain management, event planning, and product startups.

    Before joining the front-end world, I worked as a data analyst, using Excel and Excel VBA as my daily drivers. I also had the opportunity to work as a network administrator where I learned how to build and configure Linux servers.

No comments yet. Be the first to comment.