Skip to content

Latest commit

 

History

History
303 lines (222 loc) · 11.5 KB

File metadata and controls

303 lines (222 loc) · 11.5 KB

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.