Bird
Raised Fist0

In a GUI framework, you want to allow widgets to have customizable behaviors like drag, resize, and color change. Which design pattern aligns best with favoring composition over inheritance here?

easy🔍 Pattern Recognition Q2 of Q15
OOP & Design Patterns - Composition vs Inheritance - Favour Composition, Why & When
In a GUI framework, you want to allow widgets to have customizable behaviors like drag, resize, and color change. Which design pattern aligns best with favoring composition over inheritance here?
AFactory pattern to create widgets with fixed behaviors.
BDecorator pattern to add behaviors dynamically to widgets.
CSingleton pattern to manage widget behaviors globally.
DDeep inheritance hierarchy with specialized widget subclasses.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the need for dynamic behavior addition

    Widgets require flexible behavior changes without subclass explosion.
  2. Step 2: Recognize Decorator pattern role

    Decorator wraps objects to add responsibilities dynamically, fitting composition principles.
  3. Step 3: Evaluate other options

    Deep inheritance is rigid; Singleton manages global state, not behaviors; Factory creates fixed objects, not dynamic behavior.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Decorator enables dynamic behavior addition via composition [OK]
Quick Trick: Decorator pattern exemplifies composition for dynamic behavior [OK]
Common Mistakes:
MISTAKES
  • Confusing inheritance with dynamic behavior addition
  • Misapplying Singleton or Factory patterns for behavior flexibility
Trap Explanation:
PITFALL
  • Candidates often pick inheritance or factory due to familiarity, missing dynamic behavior flexibility.
Interviewer Note:
CONTEXT
  • Tests knowledge of design patterns that embody composition principles.
Master "Composition vs Inheritance - Favour Composition, Why & When" 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