Pattern: Composite

 

Synopsis

 

The Composite pattern allows you to build complex objects by recursively composing similar objects in a tree-like manner. The Composite pattern also allows the objects in the tree to be manipulated in a consistent manner, by requiring all of the objects in the tree to have a common super-class or interface.

 

Context

 

Frequently programmers develop systems in which a component may be an individual object or it may represent a collection of objects. The Composite pattern is designed to accommodate both cases. To summarize, a composite is a collection of objects, any one of which may be either a composite, or just a primitive object. In tree nomenclature, some objects may be nodes with additional branches and some may be leaves.

 

Forces

 

Use the Composite Pattern when:

 

 

Solution

 

 

 Participants:

o        Declares the interface for the objects in the composition

o        Implements default behavior for the interface common to all classes as appropriate

o        Declares an interface for accessing and managing its child components

o        (Optional) defines an interface for accessing a components parent in the recursive structure, and implements it if that is appropriate

o        Represents leaf objects in the composition. A leaf has no children

o        Defines behavior for primitive objects in the composition

o        Defines behavior for components having children

o        Stores child components

o        Implements child-related operations in the Component Interface

o        Manipulates objects in the composition through the component interface

 

 

Consequences

 

The Composite Pattern:

 

 

Implementation

 

Source Code for the implementation is in the following zip file: CompositeDemo.zip

 

Related patterns

 

·         Chain of Responsibility. (Component-parent link is used).

·         Decorator.

·         Flyweight.

·         Iterator.

·         Visitor.