Card 03/ 05
Composite vs Decorator
Both hold objects of their own interface; one holds many and combines them, the other holds one and adds to it.
Composite and Decorator are both built by recursive composition: an object that implements an interface and also holds objects of that same interface. They are told apart by counting what the object holds and looking at what it does with the result. A composite holds any number of children and combines their answers; a decorator holds exactly one object and adds to its answer. This card shows the two diagrams together and then the differences.
The diagrams differ in one field, children, a list, against inner, a single reference, and every difference in the table below follows from it.
| Question | Composite | Decorator |
|---|---|---|
| How many does it hold? | Any number, including none | Exactly one |
| What does it do with the result? | Combines the children's answers, such as a sum | Adds to the one answer, such as a log line |
| What shape do the objects form? | A tree | A chain, one wrapper inside another |
| What is it for? | Treating a group like a single item | Adding behaviour without subclassing |
The question to ask of unfamiliar code is "how many?". A folder's size that loops over its contents is a composite; a buffered stream's read that calls one inner stream is a decorator. The two can meet in one design: a menu tree is a composite, and a decorator that adds a "new" badge can wrap any node in it, a single item or a whole submenu.
← → move through sections and cards