Frontend Design Patterns Cheatsheet
1. Module Pattern
Use Case: Encapsulation and avoiding global scope.
Example:
const counter = (function () {
let count = 0;
return {
increment: () => ++count,
reset: () => (count = 0),
get: () => count
};
})();
2. Observer Pattern
Use Case: Event pub/sub, UI reactivity.
Example:
class Observable {
constructor() { [Link] = []; }
subscribe(fn) { [Link](fn); }
notify(data) { [Link](fn => fn(data)); }
3. Factory Pattern
Use Case: Create many similar objects with variations.
Example:
function createButton(type) {
return type === "primary"
? { color: "blue", size: "large" }
: { color: "gray", size: "medium" };
}
Frontend Design Patterns Cheatsheet
4. Strategy Pattern
Use Case: Swappable logic/algorithms.
Example:
const strategies = {
email: val => /\S+@\S+\.\S+/.test(val),
phone: val => /^\d{10}$/.test(val)
};
function validate(type, val) {
return strategies[type](val);
5. Singleton Pattern
Use Case: Single instance shared globally.
Example:
class Config {
constructor() {
if ([Link]) return [Link];
[Link] = {};
[Link] = this;
6. Command Pattern
Use Case: Encapsulate actions (undo/redo).
Example:
class Command {
constructor(execute, undo) {
[Link] = execute;
[Link] = undo;
}
Frontend Design Patterns Cheatsheet
Bonus: Architectural Patterns
- Container + Presentational Components: Clean separation of logic and UI.
- State Machine / State Pattern: Manage complex UI states with tools like XState.