Design Patterns: Module, Factory, Observer
Learn the architectural blueprints of software design. Discover how to encapsulate data, manufacture objects, and broadcast events using classic patterns.
Software Blueprints
A **Design Pattern** is a proven, standardized solution to a common software engineering problem. They are not specific libraries or frameworks, but conceptual templates for writing clean, maintainable code.
The Big Three in JavaScript
1. **The Module Pattern**: Used to encapsulate 'private' variables and functions, exposing only a public API. Historically achieved using Closures (IIFEs), but now natively supported via ES Modules (export/import).
2. **The Factory Pattern**: A function that creates and returns new objects without using the new keyword or classes. Ideal when the object creation process is complex.
3. **The Observer Pattern (Pub/Sub)**: A 'Subject' maintains a list of 'Observers'. When the Subject's state changes, it automatically broadcasts a notification to all subscribed Observers.
The Observer Pattern in Action
You use the Observer pattern every day without realizing it. Every time you write button.addEventListener('click', fn), the button is the *Subject*, and your function is the *Observer*.
javascript
class Subject {
constructor() { this.observers = []; }
subscribe(fn) { this.observers.push(fn); }
publish(data) {
this.observers.forEach(fn => fn(data));
}
}
When publish('hello') is called, every function sitting in the observers array executes simultaneously.
The Observer Architecture
Study the architecture diagram below. It maps out the one-to-many relationship of the Observer pattern, where a single central Subject broadcasts data to multiple independent Subscribers.
The Observer Pattern
constructor() {
this.observers = [];
}
this.observers.push(fn);
}
this.observers.forEach(fn => fn(data));
}
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Design Patterns are proven, conceptual templates for solving common architectural problems.
- The **Module Pattern** encapsulates private logic and exposes a public API.
- The **Factory Pattern** uses a function to manufacture and return objects, abstracting away complex creation logic.
- The **Observer Pattern** (Pub/Sub) allows a central Subject to maintain a list of dependents and notify them automatically of state changes.
- DOM Event Listeners and Redux stores are classic implementations of the Observer pattern.
Done with this concept?
Mark it complete to track your progress. No login needed.