JavaScript Design Patterns
What are Design Patterns?
Design patterns are reusable solutions to common software design problems. They help in writing
scalable, maintainable, and efficient code.
Types of Design Patterns
Design patterns are categorized into three main types:
1. Creational Patterns (Object Creation)
Singleton – Ensures only one instance of a class exists.
Factory Method – Creates objects without specifying the exact class.
Prototype – Creates objects by cloning an existing object.
Builder – Constructs complex objects step by step.
Abstract Factory – Provides an interface to create families of related objects.
2. Structural Patterns (Object Composition)
Adapter – Allows incompatible interfaces to work together.
Decorator – Dynamically adds behavior to objects.
Facade – Provides a simplified interface to a complex system.
Proxy – Acts as a placeholder or intermediary.
Bridge – Decouples abstraction from implementation.
Composite – Treats individual and composite objects uniformly.
Flyweight – Reduces memory usage by sharing common data.
3. Behavioral Patterns (Object Interaction)
Observer – Defines a one-to-many dependency between objects.
Strategy – Encapsulates algorithms for runtime selection.
Command – Encapsulates requests as objects for undo/redo.
Mediator – Centralizes complex communication between objects.
State – Allows an object to change behavior when its state changes.
Template Method – Defines the skeleton of an algorithm with customizable steps.
Iterator – Provides a way to access elements sequentially.
Chain of Responsibility – Passes a request along a chain of handlers.
Memento – Captures and restores an object's state.
Must-Know Patterns for JavaScript Developers
Singleton – Used in Redux Store, service instances.
Factory – Used in object creation frameworks.
Observer – Used in Event Listeners, Pub-Sub.
Decorator – Used in middleware (Express.js).
Module Pattern – Helps in encapsulation using closures.
Proxy – Used in API request handling, logging.
Strategy – Used in different authentication mechanisms.
Builder – Used in UI component libraries.
Example: Singleton Pattern
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const obj1 = new Singleton();
const obj2 = new Singleton();
console.log(obj1 === obj2); // true