Skip to content

ritik1711999/Common-Design-Patterns

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

TypeScript Design Patterns - Interview Preparation Guide

A comprehensive collection of design patterns implemented in TypeScript with real-world examples, unit tests, and interview preparation materials.

🎯 Purpose

This repository is designed to help you:

  • Master design patterns with practical TypeScript implementations
  • Prepare for interviews with common questions and answers
  • Understand when to use each pattern with real-world scenarios
  • Practice coding with fully tested, production-ready examples

πŸ“š Pattern Categories

Easier Patterns (Start Here)

These patterns are intuitive, commonly used, and frequently asked in interviews:

  1. Strategy Pattern - Encapsulate algorithms and make them interchangeable
  2. Factory Pattern - Create objects without specifying exact classes
  3. Observer Pattern - Subscribe to and receive notifications of events
  4. Decorator Pattern - Add functionality to objects dynamically
  5. Singleton Pattern - Ensure only one instance exists

Structural Patterns (Intermediate)

  1. Adapter Pattern - Make incompatible interfaces work together
  2. Facade Pattern - Provide simplified interface to complex systems
  3. Proxy Pattern - Control access to objects
  4. Composite Pattern - Treat individual and composite objects uniformly

Behavioral Patterns (Advanced)

  1. Command Pattern - Encapsulate requests as objects
  2. Template Method - Define algorithm skeleton, let subclasses override steps
  3. State Pattern - Change behavior based on internal state
  4. Chain of Responsibility - Pass requests along a chain of handlers

Creational Patterns (Advanced)

  1. Builder Pattern - Construct complex objects step by step
  2. Abstract Factory - Create families of related objects
  3. Prototype Pattern - Clone existing objects

πŸš€ Getting Started

Prerequisites

  • Node.js (v18 or higher)
  • npm or yarn

Installation

# Install dependencies
npm install

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

# Build TypeScript
npm run build

πŸ“– How to Use This Repository

For Learning

  1. Start with easier patterns (Strategy, Factory, Observer)
  2. Read each pattern's README to understand:
    • What problem it solves
    • When to use it
    • Pros and cons
  3. Study the implementation code
  4. Run and modify the tests
  5. Try implementing your own variations

For Interview Prep

  1. Review the INTERVIEW_GUIDE.md
  2. Practice explaining each pattern in your own words
  3. Memorize the UML diagrams and class structures
  4. Be ready to code patterns from scratch
  5. Understand trade-offs and alternatives

πŸ“Œ Pattern Documentation

βœ… Implemented Patterns

1. Strategy Pattern - Behavioral

  • Location: src/behavioral/strategy/
  • Tests: 25 test cases covering all scenarios
  • Real-world example: E-commerce payment processing (Credit Card, PayPal, Crypto)
  • Key concept: Encapsulate algorithms to make them interchangeable
  • Interview focus: Decision patterns, polymorphism, context switching
  • Read: Strategy Pattern Guide

2. Factory Pattern - Creational

  • Location: src/creational/factory/
  • Tests: 50 test cases with multiple factory examples
  • Real-world examples:
    • Document Factory (PDF, Word, Excel)
    • Shape Factory (Circle, Rectangle, Triangle)
    • Notification Factory (Email, SMS, Push, Slack) with registry pattern
  • Key concept: Create objects without specifying their exact classes
  • Interview focus: Encapsulation, loose coupling, extensibility
  • Read: Factory Pattern Guide

3. Observer Pattern - Behavioral

  • Location: src/behavioral/observer/
  • Tests: 40 test cases including integration tests
  • Real-world examples:
    • Stock price notification system (Traders, Portfolio Tracker, Alert Service, Logger)
    • User activity tracking system (Analytics, Notifications, Security monitoring)
  • Key concept: Define one-to-many dependency with automatic notifications
  • Interview focus: Event-driven architecture, loose coupling, pub-sub pattern
  • Read: Observer Pattern Guide

4. Decorator Pattern - Structural

  • Location: src/structural/decorator/
  • Tests: 36 test cases with decorator combinations
  • Real-world examples:
    • Coffee shop system (Milk, Sugar, Whipped Cream, Caramel, Vanilla decorators)
    • Text formatting system (Bold, Italic, Underline, Color, Highlight decorators)
    • Data stream system (Compression, Encryption, Validation, Buffering decorators)
  • Key concept: Add behavior to objects dynamically without subclassing
  • Interview focus: Composition over inheritance, decorator stacking, behavior modification
  • Read: Decorator Pattern Guide

5. Singleton Pattern - Creational

  • Location: src/creational/singleton/
  • Tests: 46 test cases covering initialization and state management
  • Real-world examples:
    • Logger singleton for application-wide logging
    • Database connection pool singleton
    • Configuration manager singleton
    • Cache manager singleton
  • Key concept: Ensure a class has only one instance with global access
  • Interview focus: Lazy initialization, thread safety, testability concerns, DI alternative
  • Read: Singleton Pattern Guide

πŸ“ Repository Structure

src/
β”œβ”€β”€ behavioral/          # Behavioral patterns
β”‚   β”œβ”€β”€ strategy/
β”‚   β”‚   β”œβ”€β”€ strategy.ts
β”‚   β”‚   β”œβ”€β”€ strategy.test.ts
β”‚   β”‚   └── README.md
β”‚   └── ...
β”œβ”€β”€ creational/          # Creational patterns
β”‚   β”œβ”€β”€ factory/
β”‚   └── ...
β”œβ”€β”€ structural/          # Structural patterns
β”‚   β”œβ”€β”€ decorator/
β”‚   └── ...
└── examples/            # Real-world examples
    └── use-cases/

πŸŽ“ Pattern Quick Reference

Implemented Patterns (βœ… Complete with Tests)

Pattern Category Difficulty Tests Location Use When
Strategy Behavioral ⭐ Easy 25 src/behavioral/strategy/ Multiple algorithms for same task
Factory Creational ⭐ Easy 50 src/creational/factory/ Object creation logic is complex
Observer Behavioral ⭐ Easy 40 src/behavioral/observer/ One-to-many event notifications
Decorator Structural ⭐⭐ Medium 36 src/structural/decorator/ Add features without subclassing
Singleton Creational ⭐ Easy 46 src/creational/singleton/ Only one instance needed

Upcoming Patterns (To Be Implemented)

Pattern Category Difficulty Use When
Adapter Structural ⭐⭐ Medium Incompatible interfaces
Facade Structural ⭐ Easy Simplify complex subsystems
Command Behavioral ⭐⭐ Medium Parameterize and queue operations
Builder Creational ⭐⭐ Medium Complex object construction
Proxy Structural ⭐⭐ Medium Control object access

πŸ’‘ Interview Tips

Most Commonly Asked Patterns

  1. Singleton - Almost always asked βœ… Implemented
  2. Factory - Very common βœ… Implemented
  3. Observer - Common for frontend roles βœ… Implemented
  4. Strategy - Common for algorithm-heavy roles βœ… Implemented
  5. Decorator - Common for all roles βœ… Implemented

Pattern Comparison Quick Guide

Strategy vs State

  • Strategy: Client chooses algorithm; behavior varies by external decision
  • State: Object changes behavior based on internal state; object controls transition

Factory vs Singleton

  • Factory: Creates instances (potentially multiple)
  • Singleton: Ensures only ONE instance exists

Decorator vs Strategy

  • Decorator: Adds behavior to objects at runtime; composition-based
  • Strategy: Encapsulates algorithm selection; composition-based

Observer vs Mediator

  • Observer: One-to-many; subjects notify observers directly
  • Mediator: Many-to-many; objects communicate through central mediator

What Interviewers Look For

  • βœ… Clear explanation of the problem the pattern solves
  • βœ… Knowledge of when NOT to use the pattern
  • βœ… Ability to implement from scratch without notes
  • βœ… Understanding of trade-offs and alternatives
  • βœ… Real-world examples from your experience
  • βœ… How to test code that uses the pattern
  • βœ… Performance implications

Red Flags to Avoid

  • ❌ Memorizing code without understanding
  • ❌ Not knowing the problems patterns solve
  • ❌ Overusing patterns where simple code would work
  • ❌ Confusing similar patterns (e.g., Strategy vs State)
  • ❌ Not being able to explain why you'd use a pattern
  • ❌ Claiming all patterns are equally useful everywhere

πŸ“Š Test Coverage Summary

Test Suites: 5 passed, 5 total
Tests:       193 passed, 193 total βœ…

Pattern Breakdown:
- Strategy:  25 tests βœ…
- Factory:   50 tests βœ…
- Observer:  40 tests βœ…
- Decorator: 36 tests βœ…
- Singleton: 46 tests βœ…

Run tests locally:

npm test              # Run all tests
npm test -- --watch  # Watch mode
npm run coverage      # Coverage report

πŸ“š Additional Resources

πŸŽ“ Next Learning Path

  1. βœ… Already completed: Strategy, Factory, Observer, Decorator, Singleton
  2. πŸ“Œ Start here: Review CHEAT_SHEET.md for quick reference
  3. πŸ“‹ Study each pattern: Start with Strategy Pattern
  4. πŸ’» Practice: Modify tests and implement your own variations
  5. 🎀 Interview prep: Use real-world examples to explain each pattern

🀝 Contributing

Feel free to:

  • Add more examples to existing patterns
  • Improve documentation or fix bugs
  • Share this with others preparing for interviews
  • Suggest new patterns to implement

This is a learning resource - improvements welcome!

πŸ“ License

MIT - Use this freely for learning and interview preparation.


Ready to start? Begin with the Strategy Pattern guide πŸš€

Need a quick review? Check out the CHEAT_SHEET.md for one-liners and decision matrices.

About

TypeScript Design Patterns with real-world examples, extensive unit tests, and interview-ready explanations. Learn when and why to use each pattern with production-style implementations.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors