Thursday, January 6, 2011

Composite Pattern: Design Pattern

Whole-Part hierarchical relationship.

















public interface Component {
    public void print();
}


public class Leaf implements Component {
    String name = "";
    public Leaf(String args) {
this.name = args;
    }
    public void print() {
System.out.println(">> " + this.name);
    }
}


public class Composite implements Component {
    String name = "";
    int index = 0;
    Component childrens[] = new Component[10];


    public void addComponent(Component arg) {
childrens[index++] = arg;
    }

    public Composite(String args) {
this.name = args;
    }


    public void print() {
System.out.println(">> " + this.name);
for (int i = 0; i < index; i++) {
          childrens[i].print();
}
    }
}


public class Client {
    public static void main(String [] args) {
         Composite main = new Composite("MAIN");
         Leaf leaf1 = new Leaf("LEAF1");
         main.addComponent(leaf1);
         Composite subMain = new Composite("subMAIN");

         Leaf leaf2 = new Leaf("LEAF2");
         Leaf leaf3 = new Leaf("LEAF3");
         subMain.addComponent(leaf2);
         subMain.addComponent(leaf3);
         main.addComponent(subMain);

         main.print();
    }
}


References:
http://sourcemaking.com/design_patterns/composite

No comments:

Post a Comment