Card 03/ 05

ComparisonDifficulty: Intermediate1 min

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.

Composite, a node holding many components
Decorator, a wrapper holding one component

The diagrams differ in one field, children, a list, against inner, a single reference, and every difference in the table below follows from it.

Composite and Decorator side by side
QuestionCompositeDecorator
How many does it hold?Any number, including noneExactly one
What does it do with the result?Combines the children's answers, such as a sumAdds to the one answer, such as a log line
What shape do the objects form?A treeA chain, one wrapper inside another
What is it for?Treating a group like a single itemAdding 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.