Composite Pattern
The Composite pattern: treating a single object and a group of objects the same way, as in files and folders.
A folder holds files and other folders, a bundle holds products and other bundles, and a window holds buttons and panels that hold more buttons. Code that works on such a tree keeps asking whether it holds one item or a group. The Composite pattern removes the question: a group and a single item share one interface, and the group answers each call by asking its children.
This topic opens on that problem and the intent, then reads the three participants off the class diagram, where a composite holds a list of components and so can hold other composites. The template builds a small tree in Python, Java and TypeScript and prints it by recursion.
Two examples follow: a product bundle whose price is the sum of what it holds, and Java Swing, where a panel holds buttons and other panels. The gotcha is where to declare add: on the shared interface, so a leaf must refuse it, or on the composite alone, so the client must know which it holds. The exercise counts everyone in an organisation chart.
By the end you can recognise a composite, build one, and compute a value through a tree of any depth.
Contents
8 cardsnot started