Thursday, 8 November 2007

Composite Pattern in Java

Wikipedia says
"
Composite Pattern is a structural design pattern.Composite allows a group of objects to be treated in a same way as a single instance of the object.The intent of composite is to "compose objects into tree structures to represent part-whole hierarchies.Composites lets clients treat individual objects and compositions uniformly.This is called recursive composition
"

Problem: When dealing with tree structures often we need to discriminate between branch and leaf nodes and it is error prone.

Intent:
Composite pattern fits here to try to achieve least common denominator relationship.
Hence solution is to have an interface that allows treating objects in a complex-tree structure equally.

In OOPS this is known as "has a" relationship between objects.As discussed Operations we can perform on all composite objects often have a "least common denominator" principle where for example when resizing a shape we would expect
same behaviour for all other shapes also.

Usage: This pattern can be used when clients should ignore the difference between composition of objects and indivudual objects.

Below example gives one implementation of composite pattern.


package patterns;

interface Place {
void print();
}

class State implements Place {

List<Place> placeList=new ArrayList<Place>();

public void add(Place place) {
placeList.add(place);
}

public void remove(Place place) {
placeList.remove(place);
}

public void print() {
for(Place place:placeList) {
place.print();
    }
  }
}

class City implements Place {

private String name;

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

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

public void print() {
System.out.println("printing..." + name);
  }
}

public class Composite {

public static void main(String[] args) {

State s1=new State();
State s2=new State();
State s3=new State();

City c1=new City("City1");
City c2=new City("City2");
City c3=new City("City3");

s1.add(c1);
s2.add(c2);
s3.add(s1);
s3.add(s2);
s3.add(c3);
s3.print();
  }

}

Prints as expected:
printing...City1
printing...City2
printing...City3

Hope this explanation helps.

3 comments:

Unknown said...

Hi Prashanth,
i saw your design patterns post in DZONE. Its a good post & easy to read & remember
Keep it up
Nagesh

Unknown said...

Hi Prashanth,
i saw your design patterns post in DZONE. Its a good post & easy to read & remember
Keep it up
Nagesh

JP said...

Nagesh,

Thanks a lot for encouragement.Please do provide your website if applicable so that i may also view it.

Thanks
Prashant