当我看到这个模式的时候,我真的惊呆了,我联想起平时我们的for循环与迭代器。
1 public class Test { 2 3 public static void main(String[] args) { 4 List list = new ListImpl(); 5 list.add("a"); 6 list.add("b"); 7 list.add("c"); 8 //第一种迭代方式 9 Iterator it = list.iterator(); 10 while (it.hasNext()) { 11 System.out.println(it.next()); 12 } 13 14 System.out.println("====="); 15 //第二种迭代方式 16 for (int i = 0; i < list.getSize(); i++) { 17 System.out.println(list.get(i)); 18 } 19 } 20 } 1 public interface List { 2 3 Iterator iterator(); 4 5 Object get(int index); 6 7 int getSize(); 8 9 void add(Object obj); 10 } 1 public class ListImpl implements List { 2 3 private Object[] list; 4 5 private int index; 6 7 private int size; 8 9 public ListImpl() { 10 index = 0; 11 size = 0; 12 list = new Object[100]; 13 } 14 15 public Iterator iterator() { 16 return new IteratorImpl(this); 17 } 18 19 public Object get(int index) { 20 return list[index]; 21 } 22 23 public int getSize() { 24 return this.size; 25 } 26 27 public void add(Object obj) { 28 list[index++] = obj; 29 size++; 30 } 31 } 1 public interface Iterator { 2 3 Object next(); 4 5 void first(); 6 7 void last(); 8 9 boolean hasNext(); 10 } 1 public class IteratorImpl implements Iterator { 2 3 private List list; 4 5 private int index; 6 7 public IteratorImpl(List list) { 8 index = 0; 9 this.list = list; 10 } 11 12 public void first() { 13 index = 0; 14 } 15 16 public void last() { 17 index = list.getSize(); 18 } 19 20 public Object next() { 21 Object obj = list.get(index); 22 index++; 23 return obj; 24 } 25 26 public boolean hasNext() { 27 return index < list.getSize(); 28 } 29 }
转载于:https://www.cnblogs.com/huzi007/p/3885370.html