Behavioural Design Pattern: Iterator Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Behavioural Design Pattern: Iterator Pattern

Share This



The Iterator Pattern, as defined by the Gang of Four (GoF), is employed to progressively access the elements of an aggregate object while keeping its underlying implementation hidden.

The Iterator pattern is commonly referred to as the Cursor pattern.

In the collection framework, the preferred method of iteration is now using the Iterator interface instead of the Enumeration interface provided by the java.util package.The Iterator interface employs the Iterator Design Pattern.

The advantage of using the Iterator Pattern is that it provides a way to access the elements of a collection sequentially without exposing its underlying structure. This allows for a more flexible and modular design, since it decouples the client code from the implementation details of the collection.

It enables several ways of moving through a collection. It streamlines the user interface for accessing the collection.

The Iterator Pattern is used to traverse and access elements of a collection in a sequential manner, without exposing the underlying structure of the collection.

It is used
  • When you desire to retrieve a group of entities without revealing their internal structure. 
  • When the collection needs to handle numerous traversals of objects.

Source code Iterator.java
package com.t4b.test.java.dp.bp.ip; interface Iterator { public boolean hasNext(); public Object next(); }
Source code WordBag.java
package com.t4b.test.java.dp.bp.ip; class WordBag { public String words[] = { "R", "J", "A", "L" }; public Iterator getIterator() { return new WordIterator(); } class WordIterator implements Iterator { int index; @Override public boolean hasNext() { if (index < words.length) { return true; } return false; } @Override public Object next() { if (this.hasNext()) { return words[index++]; } return null; } } }
Source code TestMain.java
package com.t4b.test.java.dp.bp.ip; public class TestMain { public static void main(String[] args) { WordBag bag = new WordBag(); for (Iterator iter = bag.getIterator(); iter.hasNext();) { String name = (String) iter.next(); System.out.println("Name : " + name); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.