What is the difference between Decorator and Composite?
Answer
Both Decorator and Composite use recursive composition and share the same component interface, which is why they are often confused. The key differences: Decorator always wraps a single child and adds behavior to it — its purpose is feature augmentation. Composite wraps multiple children and aggregates them — its purpose is representing tree structures. In a Decorator, the relationship is 1-to-1; in a Composite, it is 1-to-many. You can often combine them: a file system uses Composite for the folder/file hierarchy, and then you can decorate specific files with an encryption decorator. Decorator's chain is linear; Composite's structure is a tree.
Previous
How can you combine the Decorator and Strategy patterns?
Next
What is the difference between Observer and Mediator?
More Design Patterns (Gang of Four) Questions
View all →- Intermediate What is the Template Method design pattern?
- Intermediate What is the Visitor design pattern?
- Intermediate What is the difference between Factory Method and Abstract Factory?
- Intermediate When should you NOT use design patterns?
- Intermediate How are the Gang of Four patterns categorized?