Design Patterns
Design patterns are reusable solutions to common software design problems. They were popularized by the "Gang of Four" (GoF) book and provide proven approaches to recurring design challenges.
Singleton Pattern
SINGLETON PATTERN
=================
Ensures only ONE instance of a class exists.
+-------------------+
| Database |
+-------------------+
| - static instance | <--- Only one exists
+-------------------+
| + getInstance() |
| + connect() |
| + query() |
+-------------------+
Usage:
const db1 = Database.getInstance();
const db2 = Database.getInstance();
// db1 === db2 (same instance)
Best for: Database connections, logging, configuration
Factory Pattern
FACTORY PATTERN
===============
Creates objects without specifying exact class.
+------------------+
| Factory |
+------------------+
| + create(type) |
+--------+---------+
|
v
+--------+---------+
| |
v v v v
+---+ +---+ +---+ +---+
| A | | B | | C | | D |
+---+ +---+ +---+ +---+
Usage:
const shape = ShapeFactory.create("circle");
// Returns a Circle object
Best for: When object creation is complex or varies
Observer Pattern
OBSERVER PATTERN
================
Defines a one-to-many dependency between objects.
+------------+
| Subject |
+------------+
| - observers|
| + subscribe|
| + notify |
+------+-----+
|
| notifies
v
+------+-----+-----+-----+
| | | | |
v v v v v
+--+ +--+ +--+ +--+ +--+
|O1| |O2| |O3| |O4| |O5|
+--+ +--+ +--+ +--+ +--+
Usage:
eventEmitter.on('click', handler);
// Handler is notified when click occurs
Best for: Event systems, pub/sub, reactive programming
Pattern Categories
+----------------+----------------------------------+
| Category | Purpose |
+----------------+----------------------------------+
| Creational | How objects are created |
| | (Singleton, Factory, Builder) |
+----------------+----------------------------------+
| Structural | How objects are composed |
| | (Adapter, Decorator, Proxy) |
+----------------+----------------------------------+
| Behavioral | How objects communicate |
| | (Observer, Strategy, Command) |
+----------------+----------------------------------+
Key Takeaways
- Design patterns provide proven solutions to common problems
- Singleton ensures a single instance
- Factory creates objects without specifying exact classes
- Observer defines one-to-many dependencies for event handling