Cursor
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Real-world example
Treasure chest contains a set of magical items. There multiple types of items such as rings, potions, and weapons. The items can be browsed by type using an iterator the treasure chest provides.
In plain words
Containers can provide a representation agnostic iterator interface to provide access to the elements.
Wikipedia says
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements.
Programmatic Example
The main class in our example is the TreasureChest
that contains items.
1public class TreasureChest {
2
3 private final List<Item> items;
4
5 public TreasureChest() {
6 items = List.of(
7 new Item(ItemType.POTION, "Potion of courage"),
8 new Item(ItemType.RING, "Ring of shadows"),
9 new Item(ItemType.POTION, "Potion of wisdom"),
10 new Item(ItemType.POTION, "Potion of blood"),
11 new Item(ItemType.WEAPON, "Sword of silver +1"),
12 new Item(ItemType.POTION, "Potion of rust"),
13 new Item(ItemType.POTION, "Potion of healing"),
14 new Item(ItemType.RING, "Ring of armor"),
15 new Item(ItemType.WEAPON, "Steel halberd"),
16 new Item(ItemType.WEAPON, "Dagger of poison"));
17 }
18
19 public Iterator<Item> iterator(ItemType itemType) {
20 return new TreasureChestItemIterator(this, itemType);
21 }
22
23 public List<Item> getItems() {
24 return new ArrayList<>(items);
25 }
26}
Here’s the Item
class:
1public class Item {
2
3 private ItemType type;
4 private final String name;
5
6 public Item(ItemType type, String name) {
7 this.setType(type);
8 this.name = name;
9 }
10
11 @Override
12 public String toString() {
13 return name;
14 }
15
16 public ItemType getType() {
17 return type;
18 }
19
20 public final void setType(ItemType type) {
21 this.type = type;
22 }
23}
24
25public enum ItemType {
26
27 ANY, WEAPON, RING, POTION
28
29}
The Iterator
interface is extremely simple.
1public interface Iterator<T> {
2
3 boolean hasNext();
4
5 T next();
6}
In the following example, we iterate through the ring-type items found in the chest.
1var itemIterator = TREASURE_CHEST.iterator(ItemType.RING);
2while (itemIterator.hasNext()) {
3 LOGGER.info(itemIterator.next().toString());
4}
Program output:
1Ring of shadows
2Ring of armor
Use the Iterator pattern