Skip to content
intermediatePhase 49 · Low-Level Design

Design Patterns

Recognize and apply creational, structural, and behavioral patterns.

1h
0 problems
Topic Progress0%

Pattern Categories

Design patterns are reusable solutions to common design problems. They are organized into three categories.

The Gang of Four (GoF) Patterns

23 Classic Design Patterns
├── Creational Patterns (5)
│   ├── Abstract Factory
│   ├── Builder
│   ├── Factory Method
│   ├── Prototype
│   └── Singleton
│
├── Structural Patterns (7)
│   ├── Adapter
│   ├── Bridge
│   ├── Composite
│   ├── Decorator
│   ├── Facade
│   ├── Flyweight
│   └── Proxy
│
└── Behavioral Patterns (11)
    ├── Chain of Responsibility
    ├── Command
    ├── Iterator
    ├── Mediator
    ├── Memento
    ├── Observer
    ├── State
    ├── Strategy
    ├── Template Method
    ├── Visitor
    └── Interpreter

Pattern Categories Explained

Category Purpose Question It Answers
Creational Object creation mechanisms "How do I create objects?"
Structural Object composition and relationships "How do I structure classes?"
Behavioral Object communication and responsibility "How do objects interact?"

Pattern Selection Guide

Need to create objects flexibly?
├── Only one instance? → Singleton
├── Complex construction? → Builder
├── Different types? → Factory Method / Abstract Factory
└── Clone existing? → Prototype

Need to compose classes?
├── Incompatible interfaces? → Adapter
├── Simple interface to complex subsystem? → Facade
├── Add behavior dynamically? → Decorator
├── Tree structure? → Composite
└── Control access? → Proxy

Need to manage behavior?
├── One-to-many notification? → Observer
├── Change behavior with state? → State
├── Swap algorithms? → Strategy
├── Define algorithm skeleton? → Template Method
├── Pass request through chain? → Chain of Responsibility
└── Encapsulate request? → Command

Why Patterns Matter

  1. Shared vocabulary: Common language for developers
  2. Proven solutions: Battle-tested approaches
  3. Flexibility: Patterns enable change
  4. Reusability: Apply solutions across projects
  5. Best practices: Encode design wisdom

Creational Patterns

Creational patterns handle object creation mechanisms, trying to create objects in a manner suitable to the situation.

Overview

Pattern Purpose Key Benefit
Factory Method Create objects without specifying exact class Flexibility
Abstract Factory Create families of related objects Consistency
Builder Construct complex objects step by step Readability
Prototype Clone existing objects Performance
Singleton Ensure single instance Shared state

Factory Method

// Define interface for creating objects
public interface NotificationFactory {
    Notification create();
}

public class EmailFactory implements NotificationFactory {
    public Notification create() { return new EmailNotification(); }
}

public class SMSFactory implements NotificationFactory {
    public Notification create() { return new SMSNotification(); }
}

// Usage
NotificationFactory factory = getFactory(type);
Notification notification = factory.create();
notification.send(message);

Builder

// Complex object with many optional parameters
User user = new User.Builder()
    .name("John Doe")
    .email("john@example.com")
    .age(30)
    .role(Role.ADMIN)
    .build();

// vs Constructor with many parameters
User user = new User("John Doe", "john@example.com", 30, 
                     Role.ADMIN, null, null, null);

Singleton

public class DatabaseConnection {
    private static DatabaseConnection instance;
    
    private DatabaseConnection() { }
    
    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }
}

When to Use Creational Patterns

Situation Pattern
Only one instance needed Singleton
Complex object construction Builder
Different object types based on input Factory Method
Family of related objects Abstract Factory
Expensive object creation Prototype

Structural Patterns

Structural patterns deal with object composition, creating relationships between objects to form larger structures.

Overview

Pattern Purpose Key Benefit
Adapter Convert one interface to another Compatibility
Composite Tree of uniform objects Transparency
Decorator Add behavior dynamically Flexibility
Facade Simplify complex subsystem Simplicity
Proxy Control access to object Control

Adapter Pattern

// Old interface
public interface LegacyPayment {
    void makePayment(double amount);
}

// New interface
public interface ModernPayment {
    PaymentResult process(Money amount, PaymentDetails details);
}

// Adapter
public class PaymentAdapter implements ModernPayment {
    private LegacyPayment legacy;
    
    public PaymentResult process(Money amount, PaymentDetails details) {
        legacy.makePayment(amount.getAmount());
        return new PaymentResult(true, "Success");
    }
}

Decorator Pattern

// Base interface
public interface DataSource {
    void writeData(String data);
    String readData();
}

// Decorator adds compression
class CompressionDecorator implements DataSource {
    private DataSource wrapped;
    
    public void writeData(String data) {
        wrapped.writeData(compress(data));
    }
}

// Decorator adds encryption
class EncryptionDecorator implements DataSource {
    private DataSource wrapped;
    
    public void writeData(String data) {
        wrapped.writeData(encrypt(data));
    }
}

// Stack decorators
DataSource source = new EncryptionDecorator(
    new CompressionDecorator(
        new FileDataSource("data.txt")
    )
);

Facade Pattern

// Complex subsystem
public class VideoConversionFacade {
    private VideoCodec codec;
    private AudioCodec audioCodec;
    private BitrateConverter bitrate;
    
    // Simplified interface
    public File convertVideo(String filename, String format) {
        codec.read(filename);
        bitrate.convert();
        audioCodec.extract(filename);
        return new File("output." + format);
    }
}

// Client uses simple interface
VideoConversionFacade facade = new VideoConversionFacade();
File mp4 = facade.convertVideo("movie.avi", "mp4");

Structural Pattern Selection

Need Pattern
Interface incompatibility Adapter
Uniform tree structure Composite
Dynamic behavior addition Decorator
Simplify complex API Facade
Control object access Proxy

Behavioral Patterns

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects.

Overview

Pattern Purpose Key Benefit
Observer One-to-many notification Loose coupling
Strategy Swap algorithms at runtime Flexibility
State Change behavior with state State management
Command Encapsulate requests Undo/redo
Template Method Algorithm skeleton Code reuse

Observer Pattern

// Subject (publisher)
public class OrderService {
    private List<OrderEventListener> listeners = new ArrayList<>();
    
    public void addListener(OrderEventListener listener) {
        listeners.add(listener);
    }
    
    public void completeOrder(Order order) {
        // Process order...
        listeners.forEach(l -> l.onOrderComplete(order));
    }
}

// Observer (subscriber)
public interface OrderEventListener {
    void onOrderComplete(Order order);
}

public class EmailNotification implements OrderEventListener {
    public void onOrderComplete(Order order) {
        emailService.send(order.getUser(), "Order complete!");
    }
}

Strategy Pattern

// Strategy interface
public interface PricingStrategy {
    Money calculatePrice(Order order);
}

// Concrete strategies
public class RegularPricing implements PricingStrategy {
    public Money calculatePrice(Order order) {
        return order.getSubtotal();
    }
}

public class PremiumPricing implements PricingStrategy {
    public Money calculatePrice(Order order) {
        return order.getSubtotal().multiply(0.9); // 10% discount
    }
}

// Context
public class PriceCalculator {
    private PricingStrategy strategy;
    
    public Money calculate(Order order) {
        return strategy.calculatePrice(order);
    }
}

Template Method Pattern

public abstract class DataExporter {
    // Template method
    public final void export(String data) {
        validate(data);
        String processed = process(data);
        format(processed);
        save(processed);
    }
    
    protected abstract void validate(String data);
    protected abstract String process(String data);
    protected void format(String data) { /* default */ }
    protected abstract void save(String data);
}

Behavioral Pattern Selection

Need Pattern
One-to-many notification Observer
Algorithm swapping Strategy
State-dependent behavior State
Request encapsulation Command
Algorithm skeleton Template Method
Request through chain Chain of Responsibility

Practice Problems

0/3solved
Design Design Patterns System

Design a scalable Design Patterns system. Cover high-level architecture, data model, and API design.

Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliability
Design Patterns Scaling

How would you scale Design Patterns to handle 10x the current load? Identify bottlenecks and solutions.

Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decomposition
Design Patterns Failure Modes

Analyze potential failure modes for Design Patterns and design mitigation strategies.

Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradation

Quiz

1. What are the three categories of design patterns?

Question 1 options

2. Which pattern category answers 'How do I create objects?'?

Question 2 options

3. Which pattern allows adding behavior dynamically?

Question 3 options

4. Which pattern is used for one-to-many notification?

Question 4 options

5. What problem does the Adapter pattern solve?

Question 5 options

Flashcards

Question

What are the 3 categories of GoF design patterns?

Answer

Creational (object creation), Structural (object composition), Behavioral (object communication). 23 patterns total.

Question

Name 3 creational patterns.

Answer

Factory Method (flexible creation), Builder (complex construction), Singleton (single instance), Abstract Factory (object families), Prototype (cloning).

Question

Name 3 structural patterns.

Answer

Adapter (interface conversion), Decorator (add behavior), Facade (simplify API), Composite (tree structure), Proxy (access control).

Question

Name 3 behavioral patterns.

Answer

Observer (notifications), Strategy (algorithm swap), State (state-dependent), Command (request encapsulation), Template Method (algorithm skeleton).

Question

How to choose the right pattern?

Answer

Identify the problem: creation → creational, composition → structural, communication → behavioral. Then match to specific pattern.

Revision Notes

Key Takeaways

  • 1.Design patterns are reusable solutions to common design problems
  • 2.Creational patterns handle object creation (Factory, Builder, Singleton)
  • 3.Structural patterns handle object composition (Adapter, Decorator, Facade)
  • 4.Behavioral patterns handle object communication (Observer, Strategy, State)
  • 5.Choose patterns based on the specific design problem you're solving

Interview Tips

  • Mention design patterns when discussing your design approach
  • Explain why you chose a specific pattern for the problem
  • Show how patterns work together in a design
  • Discuss trade-offs of using specific patterns

Cheat Sheet

Design Patterns - Cheat Sheet

3 Categories:

Category Purpose Examples
Creational Object creation Factory, Builder, Singleton
Structural Object composition Adapter, Decorator, Facade
Behavioral Object communication Observer, Strategy, State

Creational:

  • Factory: Create without specifying class
  • Builder: Complex object step by step
  • Singleton: Single instance

Structural:

  • Adapter: Interface conversion
  • Decorator: Dynamic behavior
  • Facade: Simplify complex API

Behavioral:

  • Observer: One-to-many notification
  • Strategy: Swap algorithms
  • State: State-dependent behavior

Selection:

  1. Identify problem category
  2. Match specific pattern
  3. Apply and adapt