Bird
Raised Fist0

If you want to allow decorators to be added and removed dynamically at runtime (e.g., undo last added decorator), which modification to the Decorator Pattern implementation is most appropriate?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
If you want to allow decorators to be added and removed dynamically at runtime (e.g., undo last added decorator), which modification to the Decorator Pattern implementation is most appropriate?
AModify the base class to include flags for each decorator feature
BUse inheritance to create new subclasses for every add/remove combination
CStore decorators in a stack data structure and update the wrapped object reference on add/remove
DCache all possible decorator combinations in a lookup table
Step-by-Step Solution
  1. Step 1: Understand dynamic add/remove requirement

    Need to add or remove decorators at runtime without subclass explosion or code changes.
  2. Step 2: Identify suitable data structure and pattern modification

    Using a stack to track decorators allows pushing and popping decorators, updating the wrapped object reference accordingly.
  3. Step 3: Evaluate other options

    Inheritance and flags lead to rigidity; caching all combinations is infeasible for many decorators.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Stack structure supports dynamic decorator management efficiently [OK]
Quick Trick: Stack supports dynamic add/remove of decorators [OK]
Common Mistakes:
MISTAKES
  • Trying to use inheritance for dynamic behavior
  • Modifying base class breaks open-closed principle
Trap Explanation:
PITFALL
  • Inheritance and flags seem simpler but don't support dynamic runtime changes well.
Interviewer Note:
CONTEXT
  • Checks candidate's ability to adapt decorator pattern for dynamic behavior management.
Master "Decorator Pattern - Wrapping Behaviour Without Subclassing" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes