Wednesday, August 4, 2010

Composite Design Pattern

It is a collection of objects, anyone of which can be either a composite or just a primitive object. It enables us to represent a single object or a collection of objects using the same interface.

Example

  • If we are designing a runtime system structure for java program, we can implement it in a tree form where every node can be a executable piece of statement and it may have other nodes in it (which should be executed before it) or may be a leaf node, which just need to execute itself and return the result to the parent (or makes the changes in shared state cache).
  • If we are designing a system to display the employee structuring of an organization. It could be in tree form or in any other form. But designing the data structure using composite pattern can easily manage the requirements for hierarchy structure, where any employee work as individual or may have a number of other employees as sub-ordinates. 

When to Use

  • If we need to design a tree like structure where any node can be a leaf or a composite node again, and all this can be calculated dynamically at runtime.
  • When we want to make the system very generic, using a single interfaces which can accommodate a primitive as well as composite elements. 

Usage

  • It makes the system very generic.
  • It is easy to add a new component to any existing composite structure and the existing core framework can operate on new components as well without making any modification.
  • It is very easy to replace any existing component from the hierarchy. 

Drawbacks

  • It results in over generic structure, which sometimes unable to enforce any validations rule on the components to be added.

No comments:

Post a Comment