Friday, February 4, 2011

Structural Design Pattern : Composite

Composite Design Pattern:
Word composite mean object contain another object.

Composite Pattern is Tree Structure of simple and composite objects to represent part-whole hierarchy.


Classic real time Example is the Family hierarchy. Lets try to put it into some design


( Click to enlarge)


Code:

Component:

package com.milind.gof.structural.composite;

/**
*
* @author milind
*/
public interface Family {

public void print();

}

Composite:

package com.milind.gof.structural.composite;

import java.util.ArrayList;

/**
*
* @author milind
*/
public class Parnet implements Family{


private String name;
private ArrayList arr;

public Parnet(String name) {
this.name = name;
this.arr = new ArrayList() ;
}

public void addChild(Family ch) {
this.arr.add(ch);
}

public void print() {
for(Family c : arr) {
System.out.println(c);
if(c instanceof Parnet) {
c.print();
}
}
}

@Override
public String toString() {
return "Parent: "+this.name;
}
}

Leaf:

package com.milind.gof.structural.composite;

/**
*
* @author milind
*/
public class Child implements Family{

private String name;

public Child(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {

return "Child: "+ this.name;
}

public void print() {
}
}

Client:

package com.milind.gof.structural.composite;

/**
*
* @author milind
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

Parnet dhirubhai = new Parnet("Dhirubhai");
Parnet anil = new Parnet("Anil");
Parnet mukesh = new Parnet("Mukesh");

Child anil_1 = new Child("Anil_1");
Child anil_2 = new Child("Anil_2");

Child M1 = new Child("M1");
Child M2 = new Child("M2");

//Adding Anil children
anil.addChild(anil_1);
anil.addChild(anil_2);
//Adding Mukesh Children
mukesh.addChild(M1);
mukesh.addChild(M2);
//Adding anil and Mukesj to dhirubhai.
dhirubhai.addChild(anil);
dhirubhai.addChild(mukesh);
//printing dhirubhia's family.
dhirubhai.print();
}
}

1 comment:

  1. Betway Casino NJ Review & Bonus Code for NJ and
    Play 부산광역 출장샵 Betway NJ 서귀포 출장마사지 mobile casino 속초 출장안마 and sports betting with a full range of games. Get 하남 출장샵 a $200 bonus. Get a 100% deposit bonus with the 사천 출장샵 best

    ReplyDelete