JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Essential JavaScript Design Patterns

nairihar
JavaScript in Plain English
9 min readDec 25, 2023

Generated via leonardo.ai

Design Pattern types

Design Pattern map

1. Singleton

Database connection example

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';

// here you may have other options as well ....

export default MongoClient.connect(url);

2. Factory

class User {
constructor(name) {
this.name = name;
}
}

function createUser(name) {
return new User(name);
}


const myUser = createUser('Sara');

Image example

function createImage(name) {
if (name.match(/\.jpeg$/)) {
return new JpegImage(name);
} if (name.match(/\.gif$/)) {
return new GifImage(name);
} if (name.match(/\.png$/)) {
return new PngImage(name);
}
throw new Exception('Unsupported format!');
}

3. Strategy

const ups = new UPS();
const usps = new USPS();
const fedex = new Fedex();

const shipping = new Shipping();

shipping.setStrategy(fedex);

shipping.calculate();

// YOU CAN ALSO DO THIS
// shipping.setStrategy(ups);
// shipping.setStrategy(usps);

4. Adapter

// Existing class with a different interface
class OldSystem {
requestInfo() {
return "Information from the old system.";
}
}

// Adapter to make the OldSystem compatible with the new interface
class Adapter {
constructor(oldSystem) {
this.oldSystem = oldSystem;
}

fetchDetails() {
const oldInfo = this.oldSystem.requestInfo();
return `Adapted: ${oldInfo}`;
}
}

// Using the Adapter we make OldSystem compatible with another interface
const oldSystem = new OldSystem();
const adaptedSystem = new Adapter(oldSystem);

5. Command

const calculator = new Calculator();

// Perform calculations via commands
calculator.execute(new AddCommand(100));
calculator.execute(new SubCommand(24));
calculator.execute(new MulCommand(6));
calculator.execute(new DivCommand(2));

// Reverse last two commands (undo calculations)
calculator.undo();
calculator.undo();

console.log(`Value: ${calculator.getCurrentValue()}`);

6. Module

Implementation 1

// utils.js

const privateList = [];
const privateObject = {};

function find() {
// ...
}

function each() {
// ...
}

module.exports = {
find, each
};

Implementation 2

// utils.js

const privateList = [];
const privateObject = {};

exports.find = function () {
// ...
};

exports.each = function () {
// ...
};

7. Pub/Sub

const subscriber1 = new Subscriber();
const subscriber2 = new Subscriber();

const publisher = new Publisher();

subscriber1.sub('t.me/javascript', (msg) => {
console.log(msg);
});

subscriber2.sub('t.me/javascript', (msg) => {
console.log(msg);
});

publisher.pub('t.me/javascript', 'Quiz #123');

8. Observer

const observer = new Observable();

// Subscriber 1
observer.subscribe('channelName', (msg) => console.log(msg)); // Hello
// Subscriber 2
observer.subscribe('channelName2', (msg) => console.log(msg)); // Hello

observer.notify('channel', 'Hello');

Number of Subjects

Flexibility and Scalability

The granularity of Notification

Coupling

9. Constructor

class Movie {
constructor(name, year) {
this.name = name;
this.year = year;

this.about = () => {
return `${name} movie has been shot in ${year}`;
};
}
}

const hp = new Movie('Harry Potter', 2001);
const insatiable = new Movie('John Wick', 2014);

function Movie(name, year) {
this.name = name;
this.year = year;

this.about = () => {
return `${name} movie has been shot in ${year}`;
};
}

const johnWick = new Movie('John Wick', 2014);
function createMovie(name, year) {
const about = () => {
return `${name} movie has been shot in ${year}`;
};

return {
name, year, about
};
}

Summary

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by nairihar

Sharing valuable insights on the latest tools and trends in JavaScript. nairi.dev

Responses (4)

Write a response