Skip to content
APPCITORThe Tech Blog
Esc

Behavioral – Iterator Design Pattern

August 10, 2020 2 min read

Behavioral – Iterator Design Pattern

Iterator pattern is a behavioral pattern that used to provide a standard way to go across a group of objects. This is relatively simple and frequently used design pattern. According to GoF, Iterator pattern provides a way to access the elements of an aggregate object without exposing its underlying representation.

Let’s understand iterator pattern with a simple example.

Suppose we have a list of TV news channels and the client program want to traverse through them one by one or based on the type of language. For example some clients are only interested in English news channels and want to process only them, they don’t want to process other types of news channels.

This is a java enum and it defines all the types of news channels.

“Channel” is a POJO class that has the attributes frequency and the channel type with the constructer and getters.

Here I created the interface “ChannelIterator” and it has the methods “hasNext()” and “next()” with different return types. Let’s discuss the purpose of this class with the next step.

“ChannelCollection” interface defines the contract for our collection class implementation. There are methods to add and remove a channel but there is no method that returns the list of channels. So this interface has a method called “iterator()” that returns the iterator for traversal. “ChannelIterator” interface is for this purpose.

Collection class “ChannelCollectionImpl” have inner class implementation of Iterator interface “ChannelCollection. Also “ChannelIteratorImpl” have the inner class implementation of iterator interface “ChannelIterator” so that the implementation can’t be used by any other collection. Let’s see the main program to use our collection and iterator to traverse through the collection of channels.

This program produces the following output.

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.

Thank you.

Creational Design Patterns

Singleton Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Builder Design Pattern

Structural Design Patterns

Facade Design Pattern

Decorator Design Pattern

Adapter Design Pattern

Bridge Design Pattern

Composite Design Pattern

Proxy Design Pattern

Flyweight Design Pattern

Share this article

Keep reading