Saturday, November 29, 2014

Design Pattern : Composite

Type  Structural Design Pattern


Summary

In the composite pattern, a tree structure exists where identical operations can be performed on leaves(leaf nodes) and nodes (non-leaf nodes).  It allows a group of object to be treated as an instance of a single object.

Advantage

Clients use the Component Class Interface to interact with objects in the composite structure
If call is made to a Leaf, the request is handled directly.
If call is to a Composite, it forwards the request to its child components.  


Details

A node in a tree is a class that can have children. A node class is a 'composite' class. A leaf in a tree is a 'primitive' class that does not have children. The children of a composite can be leaves or other composites.

The leaf class and the composite class share a common 'Component' interface that defines the common operations that can be performed on leaves and composites. When an operation on a composite is performed, this operation is performed on all children of the composite, whether they are leaves or composites. Thus, the composite pattern can be used to perform common operations on the objects that compose a tree.
Following are the different Elements in Composite Pattern

Component
  • is the abstraction for all components including Leaf and Non-Leaf Nodes
  • declares the interface for objects in the composition
Composite
  • Represents a composite Component (component having children, made of other Components)
  • It stores child components
  • Implements method described in the component interface.
  • Contains additional methods for adding/removing Components.
Leaf
  • represents leaf objects in the composition .
  • Leaf are the objects that does not have children's.
  • Implement the Component Interface.


Example

This example is about Mathematical Expression. An Expression is compassed of number of mathematical Operations and Operands like follows.

Expression = (1+2) + (1x2) - (2x1)

We can represent one single Operation ( say 1+2) in a node (Component) and the whole expression as  a Composite composed of individual components. The following Class Diagram shows the different Classes. 
To evaluate the whole expression we can process individual Nodes. Like traveling the Tree and processing each nodes.


Class Diagram



  

No comments :

Post a Comment