Thursday, April 26, 2012

Structural Patterns - 3.Composite Pattern

The Composite Pattern is a very simple pattern to represent a complex structure of data. Whenever in an application, if we need to design a tree structure with leaf and nodes then this pattern could be a right candidate.

This pattern treats both the nodes and the leaves in the same way as they are the parts of the same tree.A parent-child hierarchy of many levels is a complex task to handle through the code. A child can have many children so that it will become a parent by itself.

Some children may not become a parent as they may not have any children on their own. This type of relationship can be gone to the depth of any level (ex:-parent/child generations together).

Having a design to maintain or accomodate such complex structure is a hard task. Thanks to Composite pattern which makes our life easy in the above scenario.Let us consider the below class diagram explaining the Composite Pattern,


Here, we have a generic Human Interface having two implementations
a) Child
b) Parent


The child class would be a leaf node which won't have any furthur nodes attached to it whereas a parent class is composed of a list of nodes of type Human.

Again those nodes may be either parent or child. This pattern appears recursively so that we can handle theparent and child objects to any number of generations.

Find below the structure of sample data which operates over the composite pattern,



Following code snippet will explain the above mentioned structure,
 public static void main(String[] args) {
 
  Parent one=new Parent("Gen1Parent");
  Human two=new Child("Gen2Child");
  Parent three=new Parent("Gen2Parent");
  Parent four=new Parent("Gen3Parent");
  Human five=new Child("Gen3Child");
  three.add(five);
  three.add(four);
  one.add(three);
  one.add(two);


  printItems(one); //Method to print all the values from the Tree
 
 }
 

Following code snippet will show how to iterate over the list of values in order to fetch the nodes and their leaves,

 public static void printItems(Parent parent){
         System.out.println(parent.getName());
  for(Human human:parent.getChildren()){
   if(human.getType().equals("Parent")){
   
    printItems((Parent)human);
   }else{
    System.out.println(human.getName());
   }
  }
 }

No comments:

Post a Comment