JavaScript Design Patterns – Interview Notes
20-page interview-focused guide covering Singleton, Factory, Strategy, Observer, Decorator,
Dependency Injection, IoC, Repository, Adapter, and Facade.
1. Design Patterns Overview
What patterns solve, categories (Creational, Structural, Behavioral), and interview expectations.
2. Singleton
Purpose: Ensure a class has only one instance. Real-world: Logger, Config Manager. JS: class
Logger { static instance; constructor() { if ([Link]) return [Link]; [Link]
= this; } } Interview: Discuss global state tradeoffs.
3. Factory
Purpose: Centralize object creation. Real-world: Payment providers. JS: class CreditCard {} class
UPI {} function paymentFactory(type){ return type === 'upi' ? new UPI() : new CreditCard(); }
4. Strategy
Purpose: Swap algorithms at runtime. Real-world: Discount engines. JS: const strategies = {
regular: p => p, premium: p => p * 0.9 };
5. Observer
Purpose: Publish/subscribe communication. Real-world: EventEmitter, DOM events. JS: class
Subject { observers = []; subscribe(fn){ [Link](fn); } notify(data){
[Link](fn => fn(data)); } }
6. Decorator
Purpose: Add behavior without modifying existing code. Real-world: Logging, caching. JS: const
withLogging = fn => (...args) => { [Link](args); return fn(...args); };
7. Dependency Injection
Purpose: Inject dependencies instead of creating them. Benefits: Testability and loose coupling. JS:
class UserService { constructor(repo){ [Link] = repo; } }
8. Inversion of Control (IoC)
Framework/container controls object creation. Relationship with DI and service containers.
9. Repository
Purpose: Abstract data access. JS: class UserRepository { findById(id){} save(user){} }
10. Adapter
Purpose: Convert one interface into another. Real-world: Third-party APIs. JS: class StripeAdapter {
charge(amount){ return [Link](amount); } }
11. Facade
Purpose: Simplify complex subsystems. Real-world: Unified API service layer. JS: class
TravelFacade { bookTrip(){} }
12. Pattern Comparison
Factory vs Strategy vs Adapter vs Facade.
13. SOLID Principles
How patterns support maintainable systems.
14. Common Interview Questions
When to use Singleton? Factory vs Builder? Observer drawbacks?
15. Real System Design Example
E-commerce checkout using multiple patterns.
16. Testing Pattern-Based Code
Mocking repositories and injected services.
17. Anti-Patterns
God objects, excessive singletons, tight coupling.
18. Frontend Examples
React, Redux, event systems, service abstractions.
19. Backend Examples
[Link] services, repositories, DI containers.
20. Interview Cheat Sheet
Quick revision table for all 10 patterns.