Design Patterns - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Iterator Pattern

Iterator Pattern

shape Description

Iterator Pattern is a Behavioral Pattern and is mostly used in Java Collection Framework. Iterator pattern can be used in java and .net environments. Using iterator pattern, one can use aggregate object in sequential manner without exposing the implementation. Iterator Pattern has methods and interfaces that are very important and easy to implement.

shape Advantages

  • Polymorphic traversal can be done easily.
  • Decoupling of collection and algorithms can be done.
  • Configuration management can be reduced.

shape Conceptual figure

shape Examples

Creating a class FoodItem. [java] public class FoodItem { String name; float price; public Item(String name, float price)//one parameter is String type and the another is Float type { this.name = name; this.price = price; } public String toString()//as the return type is String so String datatype is used { return name + ": Rs " + price; } } [/java] Creating a class ItemsList and importing a package(java util.*;). [java]import java.util.*; public class ItemsList { List<Item> menuItems;//creating alist public Menu() { menuItems = new ArrayList<Item>(); } public void addItem(Item item) { menuItems.add(item); } public Iterator<Item> iterator() { return new MenuIterator(); } class ItemsList implements Iterator<Item> { int currentIndex = 0; public boolean hasNext()//overrides the interface method { if (currentIndex >= menuItems.size()) { return false; } else { return true; } } public Item next()//overrides the interface method { return menuItems.get(currentIndex++); } public void remove()//overrides the interface method { menuItems.remove(--currentIndex); } } } [/java] Creating a class IteratorDemo. [java]public class IteratorDemo { public static void main(String[] args) { //List of objects are created Item i1 = new Item("Pizza", 75.00f); Item i2 = new Item("Burger", 50.00f); Item i3 = new Item("chicken sandwich", 60.00f); Menu menu = new Menu(); menu.addItem(i1); menu.addItem(i2); menu.addItem(i3); System.out.println("Displaying Menu:"); Iterator<Item> iterator = menu.iterator(); while (iterator.hasNext()) { Item item = iterator.next(); System.out.println(item); } System.out.println("\nRemoving last item returned"); iterator.remove(); System.out.println("\nDisplaying Menu:"); iterator = menu.iterator(); while (iterator.hasNext()) { Item item = iterator.next(); System.out.println(item); } } } [/java]

shape Output

The result will be as follows. [java] Displaying Menu: Pizza: Rs 75.0 Burger: Rs 50.0 chicken sandwich: Rs 60.0 Removing last item returned Displaying Menu: Pizza: Rs 75.5 Burger: Rs 50.0 [/java]

Summary

shape Key Points

  • Iterator Pattern can be used along with visitor and composite pattern.
  • Iterator can be hidden because the implementation is done through collections.
  • The logic for iteration can be embedded in collections.