定义:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。
UML类图:
1 interface Iterator { 2 public Object next(); 3 public boolean hasNext(); 4 } 5 class ConcreteIterator implements Iterator{ 6 private List list = new ArrayList(); 7 private int cursor =0; 8 public ConcreteIterator(List list){ 9 this.list = list; 10 } 11 public boolean hasNext() { 12 if(cursor==list.size()){ 13 return false; 14 } 15 return true; 16 } 17 public Object next() { 18 Object obj = null; 19 if(this.hasNext()){ 20 obj = this.list.get(cursor++); 21 } 22 return obj; 23 } 24 } 25 interface Aggregate { 26 public void add(Object obj); 27 public void remove(Object obj); 28 public Iterator iterator(); 29 } 30 class ConcreteAggregate implements Aggregate { 31 private List list = new ArrayList(); 32 public void add(Object obj) { 33 list.add(obj); 34 } 35 36 public Iterator iterator() { 37 return new ConcreteIterator(list); 38 } 39 40 public void remove(Object obj) { 41 list.remove(obj); 42 } 43 } 44 public class Client { 45 public static void main(String[] args){ 46 Aggregate ag = new ConcreteAggregate(); 47 ag.add("小明"); 48 ag.add("小红"); 49 ag.add("小刚"); 50 Iterator it = ag.iterator(); 51 while(it.hasNext()){ 52 String str = (String)it.next(); 53 System.out.println(str); 54 } 55 } 56 }
时间: 2024-10-14 10:06:30