Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The composite pattern provides a robust solution to building complex systems that are made up of several smaller components. The components that make up the system may be individual objects or containers that represent collections of objects. Think of a car as a complex system that is made up of several smaller components. The car contains an engine, body, chassis, seats, tires, etc. For the sake of simplicity, let's consider a tire as an indivisible or primitive object. A car would be composed of four tires (in reality a tire contains several smaller components such as hubcap, rim, tube, etc.). Similarly, a car contains one steering wheel. However, the engine contains several smaller components such as cylinders, compressor, radiator, etc. The engine is a component of the car, but the engine itself is a collection of components. We refer to a component that is a collection of other components as a composite object. The beauty of the composite pattern is that it allows clients to treat primitive objects and composite objects the same way. For example, when adding, or removing a component, the client doesn't have to bother with figuring out if the object is a primitive or composite object. The client can just as easily remove the engine or a tire through a common interface.
A useful way to understand the composite pattern is to think of complex composite objects as hierarchical trees. We're talking about upside-down trees as in Figure 6-1, where the system begins with a root node and cascades down, subdividing into several branches.