Thursday, October 31, 2013

Composite Design Pattern Example

Composite Design Pattern: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. --By GOF BOOK


A composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality and also shows the 1-to-many  relationship or parent child  hierarchy.

Problem: In an application if we need to represent a parent and child, node and leaf hierarchy or a tree structure. Then it is difficult to represent these structures in traditional way.

Solution: By using Composite pattern it is very easy to build these kind of hierarchy or tree structure.

This pattern is very useful, especially when you building a user interface. You can treat display object and display container object the same way, without considering the differences between the two objects. It’s very common in the GUI building environment.


Composite can be used when clients should ignore the difference between compositions of objects and individual objects. If you find that you are using multiple objects in the same way, and they often have nearly identical code to handle each of them, then composite is a good choice for you. it is less complex in this situation to treat primitives and composites as homogeneous (Node)...