Bird
Raised Fist0
LLDsystem_design~25 mins

Decorator pattern in LLD - System Design Exercise

Choose your learning style10 modes available
Design: Decorator Pattern Implementation
Design and implement the decorator pattern for a simple component interface and demonstrate how to add responsibilities dynamically. Out of scope: integration with large systems or specific language syntax.
Functional Requirements
FR1: Allow dynamic addition of responsibilities to objects without modifying their code
FR2: Support multiple layers of decoration
FR3: Maintain the original object's interface so decorated objects can be used interchangeably
FR4: Enable flexible and reusable code by composing behaviors at runtime
Non-Functional Requirements
NFR1: Must not alter the original object's source code
NFR2: Should support nesting decorators without performance degradation
NFR3: Design should be simple to understand and maintain
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
Key Components
Component interface or abstract class
Concrete component implementing the interface
Decorator base class implementing the interface and holding a reference to a component
Concrete decorators extending the decorator base to add behaviors
Design Patterns
Decorator pattern structure and roles
Composition over inheritance
Open/Closed principle
Transparent decoration
Reference Architecture
  +-----------------+       +-------------------+       +---------------------+
  |   Component     |<------+ ConcreteComponent |       |   Decorator         |
  |  (Interface)    |       |  (Implements)     |       | (Implements Component) |
  +-----------------+       +-------------------+       +---------------------+
                                      ^                             |
                                      |                             |
                                      |                      +---------------------+
                                      |                      | ConcreteDecorator(s) |
                                      |                      +---------------------+
Components
Component
Interface or Abstract Class
Defines the interface for objects that can have responsibilities added dynamically.
ConcreteComponent
Class implementing Component
The original object to which additional responsibilities can be attached.
Decorator
Abstract Class implementing Component
Holds a reference to a Component object and defines the interface for decorators.
ConcreteDecorator
Class extending Decorator
Adds responsibilities to the component dynamically by overriding methods.
Request Flow
1. Client creates a ConcreteComponent instance.
2. Client wraps the ConcreteComponent with one or more ConcreteDecorator instances.
3. Client calls methods on the decorated object using the Component interface.
4. Each decorator adds its behavior before or after delegating to the wrapped component.
5. The call propagates through all decorators down to the original ConcreteComponent.
Database Schema
Not applicable for this pattern as it focuses on object structure and behavior.
Scaling Discussion
Bottlenecks
Excessive layers of decorators can cause performance overhead due to deep call chains.
Complexity in debugging when many decorators are nested.
Potential difficulty in managing state if decorators add stateful behavior.
Solutions
Limit the number of decorator layers or optimize critical decorators for performance.
Use clear logging and debugging tools to trace decorator calls.
Design decorators to be stateless or carefully manage state to avoid side effects.
Interview Tips
Time: Spend 10 minutes explaining the problem and pattern roles, 15 minutes drawing and describing the design, 10 minutes discussing scaling and trade-offs.
Explain the motivation for the decorator pattern: adding behavior without modifying original code.
Describe the roles of Component, ConcreteComponent, Decorator, and ConcreteDecorator.
Show how decorators maintain the same interface for interchangeability.
Discuss benefits like flexibility and adherence to open/closed principle.
Mention potential drawbacks and how to mitigate them.

Practice

(1/5)
1. What is the main purpose of the Decorator pattern in system design?
easy
A. To create multiple instances of a class
B. To add new features to objects without changing their original code
C. To replace an object with a completely new one
D. To store objects in a database

Solution

  1. Step 1: Understand the Decorator pattern goal

    The Decorator pattern is designed to add new behavior or features to objects dynamically without modifying their original code.
  2. Step 2: Compare options with the pattern goal

    Options B, C, and D do not describe adding features without changing code. Only To add new features to objects without changing their original code matches the pattern's purpose.
  3. Final Answer:

    To add new features to objects without changing their original code -> Option B
  4. Quick Check:

    Decorator pattern = add features without code change [OK]
Hint: Decorator adds features by wrapping, not by changing code [OK]
Common Mistakes:
  • Confusing Decorator with Factory pattern
  • Thinking it replaces objects instead of wrapping
  • Assuming it stores data instead of adding behavior
2. Which of the following is the correct way to implement a decorator in a class-based design?
easy
A. Use a global variable to store extra features
B. Modify the original class to include new methods directly
C. Delete the original class and write a new one with extra features
D. Create a new class that wraps the original class and adds new methods

Solution

  1. Step 1: Recall Decorator implementation style

    Decorator pattern uses a wrapper class that holds an instance of the original class and adds new behavior.
  2. Step 2: Evaluate each option

    Create a new class that wraps the original class and adds new methods correctly describes wrapping with a new class. Options A, B, and C do not follow the decorator pattern principles.
  3. Final Answer:

    Create a new class that wraps the original class and adds new methods -> Option D
  4. Quick Check:

    Decorator = wrapper class adding methods [OK]
Hint: Decorator wraps original class; never modifies it directly [OK]
Common Mistakes:
  • Changing original class instead of wrapping
  • Replacing class instead of extending behavior
  • Using global variables for decoration
3. Consider this pseudocode using the Decorator pattern:
class Coffee:
    def cost(self):
        return 5

class MilkDecorator:
    def __init__(self, coffee):
        self.coffee = coffee
    def cost(self):
        return self.coffee.cost() + 2

order = MilkDecorator(Coffee())
print(order.cost())

What will be the output of print(order.cost())?
medium
A. 7
B. 5
C. 2
D. Error

Solution

  1. Step 1: Understand the base cost

    The Coffee class returns 5 when cost() is called.
  2. Step 2: Calculate decorated cost

    The MilkDecorator adds 2 to the coffee cost by calling self.coffee.cost() and adding 2.
  3. Final Answer:

    7 -> Option A
  4. Quick Check:

    5 + 2 = 7 [OK]
Hint: Decorator adds to base cost by calling wrapped object's method [OK]
Common Mistakes:
  • Forgetting to call wrapped object's method
  • Returning only decorator's added cost
  • Confusing base and added costs
4. In the following code snippet, what is the main issue that prevents the decorator from working correctly?
class LoggerDecorator:
    def __init__(self, component):
        self.component = component
    def execute(self):
        print('Logging start')
        self.execute()
        print('Logging end')
medium
A. The decorator calls itself recursively causing infinite loop
B. The decorator does not call the wrapped component's execute method
C. The constructor is missing a parameter
D. The print statements are incorrect

Solution

  1. Step 1: Analyze method calls inside execute()

    The execute() method calls self.execute(), which calls itself recursively without a base case.
  2. Step 2: Identify correct call to wrapped component

    The decorator should call self.component.execute() to delegate the call, not call itself.
  3. Final Answer:

    The decorator calls itself recursively causing infinite loop -> Option A
  4. Quick Check:

    Recursive call without base case = infinite loop [OK]
Hint: Decorator must call wrapped object's method, not itself [OK]
Common Mistakes:
  • Calling self.execute() instead of wrapped component
  • Missing delegation to wrapped object
  • Ignoring recursion issues
5. You are designing a notification system where messages can be sent via Email, SMS, and Push notifications. You want to add features like encryption and logging dynamically without changing the core notification classes. How would you apply the Decorator pattern here?
hard
A. Use inheritance to create subclasses for every combination of features
B. Add encryption and logging code directly inside each notification class
C. Create decorator classes for encryption and logging that wrap notification objects
D. Store all notifications in a database and process features later

Solution

  1. Step 1: Identify need for dynamic feature addition

    Encryption and logging should be added without modifying core notification classes, so dynamic wrapping is needed.
  2. Step 2: Apply Decorator pattern for flexible feature addition

    Create decorator classes that wrap notification objects and add encryption or logging behavior dynamically.
  3. Final Answer:

    Create decorator classes for encryption and logging that wrap notification objects -> Option C
  4. Quick Check:

    Decorator pattern = dynamic wrapping for features [OK]
Hint: Wrap notifications with decorators for features, avoid code changes [OK]
Common Mistakes:
  • Modifying core classes directly
  • Using inheritance explosion for feature combos
  • Ignoring dynamic behavior needs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard