Definition:The iterator mode provides a way to access multi-State objects in a set without exposing the set.
Use Cases:When a set needs to be traversed
Class diagram:
Sample Code:
package headfirst.iterator.dinermerger;public class MenuItem {String name;String description;boolean vegetarian;double price; public MenuItem(String name, String description, boolean vegetarian, double price) {this.name = name;this.description = description;this.vegetarian = vegetarian;this.price = price;} public String getName() {return name;} public String getDescription() {return description;} public double getPrice() {return price;} public boolean isVegetarian() {return vegetarian;}public String toString() {return (name + ", $" + price + "\n " + description);}}
package headfirst.iterator.dinermerger;public interface Iterator {boolean hasNext();Object next();}
package headfirst.iterator.dinermerger;public class ArrayIterator implements Iterator {MenuItem[] items;int position = 0; public ArrayIterator(MenuItem[] items) {this.items = items;} public Object next() {MenuItem menuItem = items[position];position = position + 1;return menuItem;} public boolean hasNext() {if (position >= items.length || items[position] == null) {return false;} else {return true;}}}
Advantages:1) provides a unified method to access the collection elements. users do not need to pay attention to the underlying implementation of the Set. 2) separates the traversal set from the management set so that the set itself only focuses on management.
Disadvantages:
Similar design patterns:
Supporting internal efforts:1) One class should have only one reason for change. 2) Cohesion is used to measure the degree to which a class or module focuses only on one function. If a class contains only a group of very similar functions, we call this class highly cohesive.