Showing posts with label composite pattern. Show all posts
Showing posts with label composite pattern. Show all posts

Wednesday, 2 March 2011

Composite Pattern in Java

Composite allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Whenever we have a requirement of handling all the objects in the same structure we can go for composite pattern, where we can create a tree structure that contain both composition of objects and individual objects as nodes and treat all of them uniformly by using same operations.
A Composite contains components i.e.(composites(again can contain components) and leaf elements(cannot contain components again)).
Base Component defines an interface for all objects in the composition. The Client uses this base component class to deal with the objects in the composition. It may also provide the default behaviour for adding,removing or accessing child components. But mostly Component is an interface.
Composite: Defines beahviour of components having children and stores the child components. We can add and remove Component instances to this composite dynamically.
Leaf : Defines the behaviour for the elements in the composition. It doesn't have references to other Components
First we need to have a Component Interface.(BaseComponent where even you can give some default implementation also)

//Component
public interface Component {
public void add(Component countryComponent);
public void remove(Component countryComponent);
public Component getChild(int i);
public String getName();
public String getDescription();
public void print();
}



Then we have Leaf implementation, which further does'nt have references to other components.


//Leaf
public class Leaf implements Component{
private String name;
private String description;

public Leaf(String name,String description){
this.name = name;
this.description = description;
}

/* these three methods doesn't make
* sense for Leaf. So we can even make
* the Base Component as abstract Class
* and provide the default implementation
* instead of this approach.
*/

public void add(Component state){
System.out.println("Sorry, leaf can't have components ");
}

public void remove(Component state){
System.out.println("Sorry, leaf can't have components ");
}

public Component getChild(int i){
System.out.println("Sorry, leaf can't have components ");
throw new UnsupportedOperationException();
}

public void print(){
System.out.println("-------------");
System.out.println("Name ="+getName());
System.out.println("Description ="+getDescription());
System.out.println("-------------");
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getName() {
return name;
}

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

}



and finally the Composite Implementation which again can contain child components.


// Composite
public class Composite implements Component{
private String name;
private String description;

// list of State Components
List<Component> components = new ArrayList<Component>();

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

public void add(Component state){
components.add(state);
}

public void remove(Component state){
components.remove(state);
}

public Component getChild(int i){
return components.get(i);
}
public void print(){
System.out.println("-------------");
System.out.println("Name ="+getName());
System.out.println("Description ="+getDescription());
System.out.println("-------------");
Iterator<Component> iterator = components.iterator();
while(iterator.hasNext()){
Component component = iterator.next();
component.print();
}
}

public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}




public class Test {
public static void main(String[] args) {
Component leaf = new Leaf("leaf","No components futher");
Component composite = new Composite("composite","Again has components");
Component subcomposite = new Composite("subcomposite","Sub Composite again contain components");

Component baseComponent = new Composite("BaseComponent","Includes all other components");

baseComponent.add(leaf);
baseComponent.add(composite);
baseComponent.add(subcomposite);

baseComponent.print();
}
}


A general consideration when implementing this pattern is whether each component should have a reference to its
container (composite). The benefit of such a reference is that it eases the traversal of the tree, but it also decreases your flexibility.
There are many tradeoffs in implementing Composite. You need to balance transperency and safety with your needs.
Hope this explanation helps.
References : Applied Java Patterns by Stephen Stelting and Olav Maassen

Iterator Pattern in Java

Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation and places the responsibility where it should be.
One Real time example of Iterator Pattern is the usage of Remote Controls in Home. This example I came accross when I was reading my husband's blog and found very intresting. I will share the same example with you.
Any Remote Control we use to start pressing up and down and back keys to iterate through the channels.

public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel previousChannel(int currentChannel);
}


The Channel iterator is common for all the remote controls.It's like a specification implemented by all the remote control manufacturing companies.


public class ChannelSurfer implements Iterator{
public Channel nextChannel(int currentChannel) {
Channel channel=new Channel(currentChannel+1);
return channel;
}
public Channel previousChannel(int currentChannel) {
Channel channel=new Channel(currentChannel-1);
return channel;
}
}


public class RemoteControl {
private ChannelSurfer surfer;
public RemoteControl() {
surfer=new ChannelSurfer();
}
public Program getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}

public class Program {// ... Some specific implementation of Program class.}
}


We all know that every channel is associated with program and it's basically the program and not the channel number which a user wants to see.This applies that we can apply some logic before returning the elements through iterator.Iterator here can also be programmed to return 'the programs' straight away rather than returning the channels.
Common Java Iterator is Iterator itself.Interface Signature has been copied from the javadoc.
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
-> Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
-> Method names have been improved.

public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}


java.util.Collection interface a root interface in Collections hierarchy contains a method iterator() which returns the Iterator interface.
Hence any class implementing Collection interface should provide definition for iterator() method.But please note that there are no Guarantees concerning the order(unless this collection is an instance of some class that provides a guarantee) as List by definition guarantees ordered Collection.
When we try to view List interface which extends Collection interface it has a method iterator() which returns an Iterator over the elements in this list in proper sequence.
Now coming to ArrayList a subclass class implementing List interface - which also extends AbstractList class provides definition for iterator() method.Infact all the underlying logic sits in AbstractList class.
When we try to view code it tries to return a Itr innerClass object.

public Iterator<E> iterator() {
return new Itr();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}

 

Other Patterns



Composite Pattern
Iterators are often used to recursively traverse composite structures.
Factory Method
Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.