来源:http://www.bjsxt.com/
一、【GOF23设计模式】_迭代器模式、JDK内置迭代器、内部类迭代器
1 package com.test.iterator; 2 /** 3 * 自定义的迭代器接口 4 */ 5 public interface MyIterator { 6 void first(); //将游标指向第一个元素 7 void next(); //将游标指向下一个元素 8 boolean hasNext(); //判断是否存在下一个元素 9 10 boolean isFirst(); 11 boolean isLast(); 12 13 Object getCurrentObj(); //获取当前游标指向的对象 14 }
1 package com.test.iterator; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * 自定义的聚合类 8 */ 9 public class ConcreteMyAggregate { 10 private List<Object> list = new ArrayList<Object>(); 11 12 public void addObject(Object obj){ 13 this.list.add(obj); 14 } 15 public void removeObject(Object obj){ 16 this.list.remove(obj); 17 } 18 19 public List<Object> getList() { 20 return list; 21 } 22 public void setList(List<Object> list) { 23 this.list = list; 24 } 25 26 //获得迭代器 27 public MyIterator createIterator(){ 28 return new ConcreteIterator(); 29 } 30 31 //使用内部类定义迭代器,可以直接使用外部类的属性 32 private class ConcreteIterator implements MyIterator{ 33 34 private int cursor; //定义游标用于记录遍历时的位置 35 36 @Override 37 public void first() { 38 cursor = 0; 39 } 40 41 @Override 42 public void next() { 43 if(cursor<list.size()){ 44 cursor++; 45 } 46 } 47 48 @Override 49 public boolean hasNext() { 50 if(cursor<list.size()){ 51 return true; 52 } 53 return false; 54 } 55 56 @Override 57 public boolean isFirst() { 58 return cursor==0?true:false; 59 } 60 61 @Override 62 public boolean isLast() { 63 return cursor==(list.size()-1)?true:false; 64 } 65 66 @Override 67 public Object getCurrentObj() { 68 return list.get(cursor); 69 } 70 } 71 }
1 package com.test.iterator; 2 3 public class Client { 4 public static void main(String[] args) { 5 ConcreteMyAggregate cma = new ConcreteMyAggregate(); 6 cma.addObject("aa"); 7 cma.addObject("bb"); 8 cma.addObject("cc"); 9 10 MyIterator iter = cma.createIterator(); 11 while(iter.hasNext()){ 12 System.out.println(iter.getCurrentObj()); 13 iter.next(); 14 } 15 } 16 }