Skip to content

jenacodes/Design-patterns

Repository files navigation

Design Patterns Project

A comprehensive JavaScript implementation of essential design patterns. This project demonstrates practical examples of common design patterns used in software development.

Project Overview

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

Files and Patterns

1. FactoryDesignPatterns.js

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:

  • Chef class - Represents a chef employee
  • Cashier class - Represents a cashier employee
  • EmployeeFactory - 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);

2. IteratorDesignPatterns.js

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 with hasNext() and next() 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());
}

3. ObserverDesignPatterns.js

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 updates
  • Subject - Maintains observers and notifies them of changes

Features:

  • subscribe() - Add new observers
  • unsubscribe() - Remove observers
  • notify() - Broadcast updates to all observers

Usage Example:

const subject = new Subject();
const observer1 = new Observer("Observer 1");
subject.subscribe(observer1);
subject.notify("New Event");

4. SingletonDesignPatterns.js

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");

5. StrategyDesignPatterns.js

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 implementations
  • Shipping - 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);

Getting Started

Prerequisites

  • Node.js installed on your system
  • A JavaScript runtime environment

Running Examples

Run any pattern file individually:

node FactoryDesignPatterns.js
node IteratorDesignPatterns.js
node ObserverDesignPatterns.js
node SingletonDesignPatterns.js
node StrategyDesignPatterns.js

Design Pattern Benefits

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

When to Use Each Pattern

  • 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

Learning Resources

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

License

This project is provided for educational purposes.


Happy Learning! 🚀

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published