SOLID & Design Patterns Interview Question #57
What is the difference between Composite and Decorator?
Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate
Quick Interview Answer
Composite organizes objects into tree structures and allows individual objects and groups to be treated uniformly. Decorator wraps an object to add behavior while preserving its interface.
Detailed Explanation
Composite organizes objects into tree structures and allows individual objects and groups to be treated uniformly. Decorator wraps an object to add behavior while preserving its interface.
Both rely heavily on composition, but their intent is different. Composite models part-whole relationships, while Decorator adds responsibilities dynamically.
Code Example
Composite:
Folder -> [File, File, Folder]
Decorator:
CachingService(
LoggingService(
RealService))