Bird
Raised Fist0
LLDsystem_design~15 mins

When to use which behavioral pattern in LLD - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - When to use which behavioral pattern
What is it?
Behavioral patterns are ways to organize how objects or parts of a system interact and communicate. They help manage complex behaviors by defining clear roles and responsibilities. This topic explains when to choose each pattern to solve specific problems in system design. Understanding this helps build systems that are easier to change and maintain.
Why it matters
Without knowing when to use each behavioral pattern, systems can become messy and hard to fix or extend. Choosing the wrong pattern can lead to confusion, bugs, and wasted time. Using the right pattern makes the system clear, flexible, and easier to work with, saving effort and reducing errors in the long run.
Where it fits
Before this, you should understand basic object-oriented design and common behavioral patterns like Observer, Strategy, and Command. After this, you can learn how to combine patterns for complex systems and explore architectural patterns that build on behavioral ones.
Mental Model
Core Idea
Behavioral patterns guide how parts of a system talk and work together to handle tasks smoothly and flexibly.
Think of it like...
It's like choosing the right way to organize a team: sometimes you need a clear leader giving orders, sometimes a group that listens and reacts, or sometimes a flexible plan that can change on the fly.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   Sender      │─────▶│ Behavioral    │─────▶│ Receiver      │
│ (Client)      │      │ Pattern Logic │      │ (Handler)     │
└───────────────┘      └───────────────┘      └───────────────┘

Behavioral patterns define the middle part, deciding how Sender and Receiver interact.
Build-Up - 7 Steps
1
FoundationUnderstanding behavioral patterns basics
🤔
Concept: Behavioral patterns focus on communication and responsibility between objects.
Behavioral patterns help objects work together by defining clear ways to pass messages, handle requests, or change behavior. Examples include patterns like Observer (objects watch others), Strategy (choose behavior at runtime), and Command (encapsulate requests).
Result
You know that behavioral patterns solve problems about how parts of a system interact, not just how they are built.
Understanding that behavioral patterns organize communication helps you see why they improve flexibility and reduce tight coupling.
2
FoundationCommon behavioral patterns overview
🤔
Concept: Learn the main behavioral patterns and their purpose.
Key patterns include: - Observer: lets objects watch and react to changes. - Strategy: lets you swap algorithms or behaviors easily. - Command: wraps requests as objects to queue or log them. - Iterator: provides a way to access elements without exposing structure. - State: changes behavior when internal state changes. - Mediator: centralizes communication between objects. - Chain of Responsibility: passes requests along a chain until handled.
Result
You can name common behavioral patterns and understand their basic use cases.
Knowing the variety of patterns prepares you to match problems with the right solution.
3
IntermediateMatching problems to patterns
🤔Before reading on: do you think Observer is best for changing behavior or for reacting to events? Commit to your answer.
Concept: Each pattern fits specific problem types in communication and behavior control.
Use Observer when many parts need to know about changes without tight links. Use Strategy when you want to switch behavior dynamically. Use Command to queue or log actions. Use State to change behavior based on internal conditions. Use Mediator to reduce complex object connections. Use Chain of Responsibility to pass requests flexibly.
Result
You can pick a pattern based on the problem type, like event notification or behavior switching.
Understanding the problem each pattern solves helps avoid misusing patterns and keeps design clean.
4
IntermediateConsidering coupling and flexibility
🤔Before reading on: do you think Mediator increases or decreases coupling between objects? Commit to your answer.
Concept: Patterns differ in how they affect object connections and system flexibility.
Observer reduces coupling by letting observers register and react without knowing details. Mediator reduces many-to-many connections by centralizing communication. Strategy and State increase flexibility by encapsulating behavior. Chain of Responsibility allows flexible request handling without fixed receivers.
Result
You understand how patterns impact system complexity and ease of change.
Knowing coupling effects guides you to choose patterns that keep systems manageable as they grow.
5
IntermediateCombining behavioral patterns effectively
🤔Before reading on: do you think combining Command and Observer can help in undo features? Commit to your answer.
Concept: Patterns can be combined to solve complex problems better than alone.
For example, Command can be combined with Observer to notify when commands execute, enabling undo or logging. State can use Strategy internally to switch behaviors. Mediator can coordinate chains of responsibility. Combining patterns leverages their strengths.
Result
You see how patterns work together to build richer, flexible systems.
Understanding pattern combinations unlocks powerful design options beyond single patterns.
6
AdvancedPerformance and scalability considerations
🤔Before reading on: do you think Observer pattern can cause performance issues if many observers exist? Commit to your answer.
Concept: Choosing patterns affects system performance and scalability in real use.
Observer can cause overhead if many observers react to frequent changes. Mediator centralizes communication but can become a bottleneck. Chain of Responsibility may add latency passing requests. Strategy and State have minimal overhead but require careful design. Consider trade-offs between flexibility and performance.
Result
You can balance design clarity with system efficiency when choosing patterns.
Knowing performance impacts prevents surprises in production and helps design scalable systems.
7
ExpertAnti-patterns and pitfalls in behavioral pattern use
🤔Before reading on: do you think overusing Mediator always simplifies design? Commit to your answer.
Concept: Misusing patterns can cause hidden complexity and maintenance headaches.
Overusing Mediator can create a 'god object' that is hard to maintain. Using Observer without careful management can cause memory leaks or unexpected updates. Applying Strategy when behavior rarely changes adds unnecessary complexity. Chain of Responsibility without clear order can cause missed requests. Recognizing these helps avoid costly mistakes.
Result
You can spot and avoid common traps in pattern application.
Understanding anti-patterns sharpens your judgment and leads to cleaner, more maintainable designs.
Under the Hood
Behavioral patterns work by defining clear roles and communication paths between objects. For example, Observer maintains a list of dependents and notifies them on changes. Strategy encapsulates algorithms in separate classes and switches them at runtime. Command wraps requests as objects, allowing queuing and undo. Internally, these patterns use references, interfaces, and delegation to decouple components.
Why designed this way?
These patterns were created to solve common problems in object communication and behavior control that arise as systems grow. They avoid tight coupling and rigid designs by promoting separation of concerns and flexibility. Alternatives like hard-coded calls or monolithic classes were harder to maintain and extend, so these patterns became standard solutions.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Client      │──────▶│ Behavioral    │──────▶│ Receiver      │
│ (Invoker)     │       │ Pattern Logic │       │ (Handler)     │
└───────────────┘       └───────────────┘       └───────────────┘

Inside Behavioral Pattern Logic:
  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐
  │ Strategy A  │  │ Strategy B  │  │ Strategy C  │
  └─────────────┘  └─────────────┘  └─────────────┘

Patterns use interfaces and delegation to switch or notify behaviors.
Myth Busters - 4 Common Misconceptions
Quick: Is the Observer pattern only useful for UI updates? Commit to yes or no.
Common Belief:Observer is mainly for updating user interfaces when data changes.
Tap to reveal reality
Reality:Observer is a general pattern for any situation where multiple parts need to react to changes, not just UI updates.
Why it matters:Limiting Observer to UI use prevents applying it to useful cases like event systems, logging, or distributed notifications.
Quick: Does using Mediator always reduce system complexity? Commit to yes or no.
Common Belief:Mediator always simplifies communication by centralizing it.
Tap to reveal reality
Reality:Mediator can simplify connections but may create a complex central object that is hard to maintain if overused.
Why it matters:Overusing Mediator leads to a 'god object' that becomes a bottleneck and maintenance nightmare.
Quick: Is Strategy pattern only about changing algorithms? Commit to yes or no.
Common Belief:Strategy is only for swapping algorithms like sorting or searching methods.
Tap to reveal reality
Reality:Strategy applies to any behavior that can vary, including validation, formatting, or decision-making logic.
Why it matters:Thinking Strategy is only for algorithms limits its use and misses opportunities for flexible design.
Quick: Does Chain of Responsibility guarantee a request will be handled? Commit to yes or no.
Common Belief:Chain of Responsibility ensures every request is handled by some object in the chain.
Tap to reveal reality
Reality:Requests can pass through the chain unhandled if no object can process them.
Why it matters:Assuming guaranteed handling can cause silent failures or missed requests in the system.
Expert Zone
1
Some behavioral patterns like State and Strategy share similar structure but differ in intent; State changes behavior based on internal state, Strategy swaps algorithms externally.
2
Observer pattern implementations must carefully manage subscriptions to avoid memory leaks, especially in languages without automatic garbage collection.
3
Mediator can be combined with event-driven architectures to centralize complex workflows but requires careful design to avoid becoming a bottleneck.
When NOT to use
Avoid using behavioral patterns when system behavior is simple and unlikely to change, as patterns add complexity. For example, do not use Strategy if only one behavior exists. Instead, use straightforward code. Also, avoid Mediator if communication is simple and direct. Alternatives include direct calls, simple callbacks, or procedural code.
Production Patterns
In real systems, Command pattern is widely used for undo/redo features and task queues. Observer is common in event-driven systems and UI frameworks. State is used in protocol handling and game AI. Mediator appears in chat systems and workflow engines. Chain of Responsibility is popular in logging frameworks and request processing pipelines.
Connections
Event-driven architecture
Behavioral patterns like Observer and Mediator build on event-driven principles.
Understanding behavioral patterns helps grasp how events flow and are handled in large distributed systems.
Human team management
Behavioral patterns mirror ways teams communicate and organize tasks.
Seeing patterns as team roles clarifies why some patterns centralize control while others distribute responsibility.
Traffic control systems
Chain of Responsibility resembles how traffic signals pass control to manage flow.
Recognizing this connection helps understand flexible request handling and prioritization.
Common Pitfalls
#1Overusing Mediator creates a complex central object.
Wrong approach:class Mediator { // Handles all communication for many objects void notifyAll() { // huge method with many conditions } }
Correct approach:class Mediator { // Coordinates communication but delegates specifics void notify(Object sender, Event e) { // simple routing logic } }
Root cause:Misunderstanding that Mediator should only coordinate, not handle all logic itself.
#2Not unsubscribing observers causes memory leaks.
Wrong approach:observerList.add(observer); // never removed // no code to remove observers
Correct approach:observerList.add(observer); // later observerList.remove(observer);
Root cause:Forgetting to manage observer lifecycle leads to unused objects staying in memory.
#3Using Strategy when behavior never changes adds needless complexity.
Wrong approach:class Context { Strategy strategy = new ConcreteStrategy(); void execute() { strategy.doAction(); } }
Correct approach:class Context { void execute() { /* fixed behavior code here */ } }
Root cause:Applying patterns without real need complicates simple code.
Key Takeaways
Behavioral patterns organize how parts of a system communicate and behave together to improve flexibility and clarity.
Choosing the right pattern depends on the problem type, such as event notification, behavior switching, or request handling.
Patterns affect system coupling and performance, so understanding their trade-offs is essential for scalable design.
Combining patterns can solve complex problems but requires careful design to avoid hidden complexity.
Misusing patterns or applying them unnecessarily leads to maintenance challenges and performance issues.

Practice

(1/5)
1. Which behavioral pattern is best suited when you want multiple objects to be notified automatically when one object changes its state?
easy
A. Observer pattern
B. Strategy pattern
C. Command pattern
D. Chain of Responsibility pattern

Solution

  1. Step 1: Understand the need for automatic notifications

    The problem requires multiple objects to be updated when one object changes state, which means a one-to-many dependency.
  2. Step 2: Match the pattern to the problem

    The Observer pattern is designed exactly for this: it lets observers subscribe to an object and get notified on changes.
  3. Final Answer:

    Observer pattern -> Option A
  4. Quick Check:

    Change notification = Observer [OK]
Hint: Notifications to many? Use Observer pattern [OK]
Common Mistakes:
  • Confusing Strategy with Observer
  • Using Command for notifications
  • Choosing Chain of Responsibility for updates
2. Which pattern allows you to change an object's behavior at runtime by switching between different algorithms or strategies?
easy
A. Observer pattern
B. Strategy pattern
C. Command pattern
D. Chain of Responsibility pattern

Solution

  1. Step 1: Identify the need for interchangeable behaviors

    The question asks about changing behavior dynamically, which means selecting algorithms or methods at runtime.
  2. Step 2: Select the pattern that supports behavior switching

    The Strategy pattern encapsulates algorithms and lets you swap them easily without changing the client code.
  3. Final Answer:

    Strategy pattern -> Option B
  4. Quick Check:

    Change behavior dynamically = Strategy [OK]
Hint: Switch algorithms easily? Use Strategy pattern [OK]
Common Mistakes:
  • Mixing Strategy with Observer
  • Using Command for behavior changes
  • Choosing Chain of Responsibility incorrectly
3. Consider this scenario: You have a request that can be handled by multiple objects in a chain. Each object decides if it can handle the request or passes it on. Which pattern fits this design?
Request -> Handler1 -> Handler2 -> Handler3
medium
A. Command pattern
B. Strategy pattern
C. Observer pattern
D. Chain of Responsibility pattern

Solution

  1. Step 1: Analyze the request handling flow

    The request passes through a chain of handlers, each deciding to handle or forward it.
  2. Step 2: Identify the matching behavioral pattern

    The Chain of Responsibility pattern allows multiple objects to handle a request in sequence until one handles it.
  3. Final Answer:

    Chain of Responsibility pattern -> Option D
  4. Quick Check:

    Request passes chain = Chain of Responsibility [OK]
Hint: Request passes chain? Use Chain of Responsibility [OK]
Common Mistakes:
  • Confusing Chain with Command
  • Using Observer for request handling
  • Choosing Strategy incorrectly
4. You have a system where commands need to be queued, logged, and executed later. Which behavioral pattern should you use? Identify the error in this choice:
Using Observer pattern to queue commands.
medium
A. Incorrect, use Command pattern instead
B. Incorrect, use Chain of Responsibility instead
C. Incorrect, use Strategy pattern instead
D. Correct use of Observer

Solution

  1. Step 1: Understand the requirement for queuing and executing commands

    Queuing, logging, and executing commands later requires encapsulating requests as objects.
  2. Step 2: Identify the pattern that encapsulates requests

    The Command pattern encapsulates requests as objects, allowing queuing and deferred execution.
  3. Step 3: Identify the error in using Observer

    Observer is for notifications, not for command encapsulation or queuing.
  4. Final Answer:

    Incorrect, use Command pattern instead -> Option A
  5. Quick Check:

    Queue commands = Command pattern [OK]
Hint: Queue commands? Use Command, not Observer [OK]
Common Mistakes:
  • Using Observer for command queuing
  • Confusing Command with Strategy
  • Choosing Chain of Responsibility wrongly
5. You are designing a notification system where users can subscribe to different event types, and the system should allow adding new event types without changing existing code. Which combination of behavioral patterns is best suited?
hard
A. Chain of Responsibility for subscriptions and Command for event handling
B. Command for subscriptions and Chain of Responsibility for event handling
C. Observer for subscriptions and Strategy for event handling
D. Strategy for subscriptions and Observer for event handling

Solution

  1. Step 1: Identify the subscription mechanism

    Users subscribing to events fits the Observer pattern, which supports dynamic subscription and notification.
  2. Step 2: Identify flexible event handling

    Strategy pattern allows interchangeable algorithms for handling different event types without changing existing code.
  3. Step 3: Combine patterns for extensibility

    Using Observer for subscriptions and Strategy for event handling supports adding new event types easily and keeps code maintainable.
  4. Final Answer:

    Observer for subscriptions and Strategy for event handling -> Option C
  5. Quick Check:

    Subscribe = Observer, flexible handling = Strategy [OK]
Hint: Subscribe = Observer, flexible handling = Strategy [OK]
Common Mistakes:
  • Mixing Command with subscriptions
  • Using Chain of Responsibility for subscriptions
  • Confusing Strategy with Observer roles