Iterator mode, also known as Cursor mode. The definition given by GOF is to provide a method to access various elements in a container object without exposing the internal details of the object.
The iterator pattern consists of the following roles:
Iterator role: The iterator role is responsible for defining the interface to access and traverse elements.
Concrete Iterator role: The specific iterator role needs to implement the iterator interface and record the current location in the traversal.
Container: The container role is responsible for providing an interface to create a specific iterator role.
Concrete Container: The specific container role implements the interface to create a specific iterator role. This specific iterator role is related to the structure of the container.
Java implementation example
Class diagram:
Code:
/** * Custom collection interface, similar to java.util.Collection * for data storage* @author stone * */ public interface ICollection<T> { IIterator<T> iterator(); //Return the iterator void add(T t); T get(int index); } /** * Custom iterator interface is similar to java.util.Iterator * Data used to traverse the collection class ICollection* @author stone * */ public interface IIterator<T> { boolean hasNext(); boolean hasPrevious(); T next(); T previous(); } /** * Collection class, depend on MyIterator * @author stone */ public class MyCollection<T> implements ICollection<T> { private T[] arys; private int index = -1; private int capacity = 5; public MyCollection() { this.arys = (T[]) new Object[capacity]; } @Override public IIterator<T> iterator() { return new MyIterator<T>(this); } @Override public void add(T t) { index++; if (index == capacity) { capacity *= 2; this.arys = Arrays.copyOf(arys, capacity); } this.arys[index] = t; } @Override public T get(int index) { return this.arys[index]; } } /* * If there is a new storage structure, you can new ICollection, corresponding to new IIterator to implement its traversal*/ @SuppressWarnings({"rawtypes", "unchecked"}) public class Test { public static void main(String[] args) { ICollection<Integer> collection = new MyCollection<Integer>(); add(collection, 3, 5, 8, 12, 3, 3, 5); for (IIterator<Integer> iterator = collection.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } System.out.println("-------------------------"); ICollection collection2 = new MyCollection(); add(collection2, "a", "b", "c", 3, 8, 12, 3, 5); for (IIterator iterator = collection2.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } } static <T> void add(ICollection<T> c, T ...a) { for (T i : a) { c.add(i); } } } }Print:
3 5 8 12 3 3 5 ------------------ abc 3 8 12 3 5