Structural Design Patterns

Composite

Description

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. (Gamma, 163)

Purpose

Composites help when dealing with structures that are made up of other structures. For example, a graphics object might be made of Lines, Rectangles, Text, and other graphic objects. A composite groups all of these objects together so they can be manipulated as a group.

Design

In order to treat objects and compositions of objects uniformly, a Composite pattern uses an abstract class that represents both primitives and their containers. This simple idea allows a developer to control a large number of items as if they were only one item or to control an individual item as needed.

UML for a generic Composite pattern (Gamma, 164)

Example

A typical customer of Autobot Robotics uses the robotic systems in a production line with one product or another acting sequentially or simultaniously. The task of organizing these production tasks can be daunting. To simplify the problem, the designers created an abstraction of the tasks so each task either stands alone or it is made up of other tasks. This allows the designers to easily refer to large groups of tasks that work together as a single unit and manipulate them as a single unit instead of having to work with dozens of tasks each individually.

Criticisms

It can make the design overly general. Sometime it is important to differentiate between the different paths and layers of the tree.