标签:turn ret while pat lis print strong his 哈希
提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。
迭代器模式的结构
Container
package design.pattern.iterator; public interface Container { public Iterator getIterator(); }
Iterator
package design.pattern.iterator; public interface Iterator { public boolean hasNext(); public Object next(); }
ConcreteContainer
package design.pattern.iterator; public class ConcreteContainer implements Container { private int[] arr = {0, 1, 2, 3, 4, 5}; @Override public Iterator getIterator() { return new ConcreteIterator(); } private class ConcreteIterator implements Iterator { private int index=0; @Override public boolean hasNext() { return index < arr.length; } @Override public Object next() { if (!this.hasNext()) return null; return arr[index++]; } } }
Client
package design.pattern.iterator; public class Client { public static void main(String[] args) { Iterator it = new ConcreteContainer().getIterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
标签:turn ret while pat lis print strong his 哈希
原文地址:http://www.cnblogs.com/m2492565210/p/7461553.html