Composite

 
Purpose Compose objects into tree structures to represent part-whole hierarchies (aka group hierarchy). With composite, both individual objects and compositions are treated uniformly by the client.

Applications that recursively allow collections of objects to be grouped, such as graphics applications (e.g., drawing editors), often are viewed favorably by the user. To better exploit the polymorphism in such applications, the composite pattern embraces the recursive nature of the "group" structure ("group" is not being used here in the algebraic sense of the word). An example of this appears below.
Example of composite pattern
Structure Composite pattern
Consequences
  • Good: Simplifies client, since composite structures can be operated on polymorphically.
  • Good: Simplifies adding/subtracting leaf types.
  • Bad: Overly general, if neither advantage mentioned above applies.
Implementation
  • Should children have references to their parent? Generally, this is a good idea.
  • Component interface should include all common operations.
  • Child ordering is best managed with an Iterator pattern, if applicable.
Sample Code
Related Patterns The Iterator pattern (see Implementation issues).