A comprehensive JavaScript implementation of essential design patterns. This project demonstrates practical examples of common design patterns used in software development.
This repository contains implementations of five fundamental design patterns:
- Factory Pattern - Object creation
- Iterator Pattern - Collection traversal
- Observer Pattern - Event-based communication
- Singleton Pattern - Single instance management
- Strategy Pattern - Algorithm selection
Purpose: Encapsulates object creation logic
The Factory pattern creates objects without specifying their exact classes. This example demonstrates creating different employee types (Chef, Cashier) through a factory.
Key Components:
Chefclass - Represents a chef employeeCashierclass - Represents a cashier employeeEmployeeFactory- Factory class that creates employees based on type
Usage Example:
const employeeFactory = new EmployeeFactory();
const chef = employeeFactory.create("SpongeBob", 1);
const cashier = employeeFactory.create("Squidward", 2);Purpose: Traverse collections without exposing their underlying representation
The Iterator pattern provides a way to access elements sequentially from a collection. This example shows backward iteration through an array.
Key Components:
ItemIterator- Provides iteration interface withhasNext()andnext()methods
Features:
- Backward traversal through collection
- No exposure of internal data structure
- Simple interface for collection navigation
Usage Example:
const iter = new ItemIterator(items);
while (iter.hasNext()) {
console.log(iter.next());
}Purpose: Define one-to-many dependency between objects for event-driven architecture
The Observer pattern enables automatic notification of multiple observers when a subject's state changes.
Key Components:
Observer- Represents objects that watch for updatesSubject- Maintains observers and notifies them of changes
Features:
subscribe()- Add new observersunsubscribe()- Remove observersnotify()- Broadcast updates to all observers
Usage Example:
const subject = new Subject();
const observer1 = new Observer("Observer 1");
subject.subscribe(observer1);
subject.notify("New Event");Purpose: Ensure a class has only one instance and provide global access to it
The Singleton pattern restricts instantiation to a single object. This example implements a Logger singleton with timestamp support and log levels.
Key Components:
Logger- Singleton class managing application logs- Log levels:
info(),warn(),error()
Features:
- Single instance throughout application
- Timestamp generation
- Multiple log level support
- Log storage and retrieval
Usage Example:
const logger1 = new Logger();
const logger2 = new Logger(); // Same instance as logger1
logger1.info("Application started");
logger1.warn("Warning message");Purpose: Define family of algorithms and make them interchangeable
The Strategy pattern allows selecting an algorithm at runtime. This example demonstrates shipping cost calculation with different carriers.
Key Components:
Fedex,Ups,Usps- Concrete strategy implementationsShipping- Context class that uses strategies
Features:
- Interchangeable shipping algorithms
- Runtime strategy selection
- Flexible algorithm switching
Usage Example:
const shipping = new Shipping();
shipping.setStrategy(new Fedex());
const cost = shipping.calculate(package);- Node.js installed on your system
- A JavaScript runtime environment
Run any pattern file individually:
node FactoryDesignPatterns.js
node IteratorDesignPatterns.js
node ObserverDesignPatterns.js
node SingletonDesignPatterns.js
node StrategyDesignPatterns.js| Pattern | Benefit |
|---|---|
| Factory | Decouples object creation from usage |
| Iterator | Provides uniform way to traverse collections |
| Observer | Promotes loose coupling in event systems |
| Singleton | Ensures controlled access to shared resources |
| Strategy | Enables runtime algorithm selection |
- Factory Pattern: When you need flexible object creation logic or want to reduce coupling between classes
- Iterator Pattern: When you need to traverse complex collections without exposing structure
- Observer Pattern: When you need to implement publish-subscribe functionality or event handling
- Singleton Pattern: When you need exactly one instance of a class (logging, configuration)
- Strategy Pattern: When you have multiple ways to perform a task and want to select at runtime
These patterns are fundamental to software design. Understanding them helps in:
- Writing maintainable code
- Reducing code duplication
- Improving code flexibility and reusability
- Facilitating team communication through common patterns
This project is provided for educational purposes.
Happy Learning! 🚀