Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data.
We use iterators quite frequently in everyday life. For example, remote control of TV. Any remote control we use, either at home/hotel or at a friend's place, we just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels.
What sort of interface can Iterator be in case of Remote Controls?
/** | |
| public Channel nextChannel(int currentChannel); |
}// End of interface |
The channel iterator is common for all the remote controls. It's like a specification implemented by all the remote control manufacturing companies.
/** | |||
| /** | ||
|
| Channel channel = new Channel(currentChannel+1); | |
| } |
|
|
| /** | ||
|
|
| Channel channel = new Channel(currentChannel-1); |
| } |
| |
}// End of class |
/** | |||
| private ChannelSurfer surfer; public RemoteControl() { | ||
|
| surfer = new ChannelSurfer(); | |
| } |
| |
| /** | ||
|
| return new Program(surfer.nextChannel()); | |
| } |
|
|
}// End of class |
We all know that every channel is associated to a program and it's basically the program and not the channel number which a user wants to see. And so, the implementation which returns a program for channels surfed.
This tells us that we can apply some logic before returning the elements through iterator. We can set rules. The Iterator here, can also be programmed to return the 'programs' straight away rather than returning the channels.
The common Java iterator is Enumeration which has implicit
hasMoreElements()
and nextElement() methods.
The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
No comments:
Post a Comment