View RSS Feed

My Java Tips

Behavioral Pattern - Iterator Pattern (Example)

Rate this Entry
by , 11-07-2011 at 06:45 PM (1622 Views)
The aim is to iterate through a collection of data using a common interface and more importantly, underlying implementation should not be known. We have a behavioral design pattern called ‘Iterator Pattern’ for this. I will introduce you to it in this post.


Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data.
I will take an example of daily life and will show how to use iterator pattern in that. You must have used a TV remote control. We use it to change channels. Normal operations are next channel or back channel. Now interesting thing is that different remote controls have different implementation/technology, but still the interface is the same and that is the reason that you are able to use it easily.

Java Code:
public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel prevChannel(int currentChannel);
}// End of interface
We declared two methods in the interface that have to be implemented in the class that implements this interface.


The defined channel iterator will be common for all the remote controls. So we know which method will do our required task, but the method has to be implemented by the class implementing this interface.


Continuing with the example, I present the ChannelSurfer class that implements the Iterator interface and thus overrides prevChannel and nextChannel methods.

Java Code:
public ChannelSurfer implements Iterator {

public Channel nextChannel (int currentChannel) {
Channel channel = new Channel(currentChannel+1);
return channel;
}	 

public Channel prevChannel (int currentChannel) {
Channel channel = new Channel(currentChannel-1);
return channel;
}
}// End of class
The following class used the whole thing to make use of it.
Java Code:
public class RemoteControl {
private ChannelSurfer surfer;
private Settings settings;
public RemoteControl() {

surfer = new ChannelSurfer();
settings = new Settings();
}	 

public getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}// End of class
I hope this helps.

Submit "Behavioral Pattern - Iterator Pattern (Example)" to Facebook Submit "Behavioral Pattern - Iterator Pattern (Example)" to Digg Submit "Behavioral Pattern - Iterator Pattern (Example)" to del.icio.us Submit "Behavioral Pattern - Iterator Pattern (Example)" to StumbleUpon Submit "Behavioral Pattern - Iterator Pattern (Example)" to Google

Tags: None Add / Edit Tags
Categories
Design Patterns

Comments