java设计模式之迭代子模式

来源:互联网 发布:网络中立规则 编辑:程序博客网 时间:2024/06/13 07:30
定义
在软件构建过程中,集合对象内部结构常常变化各异,但对于这些集合对象,我们希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为同一种算法在多种集合对象上进行操作提供了可能。
使用面向对象技术将这种遍历机制抽象为“迭代器对象”为“应对变化中的集合对象”提供了一种优雅的方式。
迭代子(Iterator)模式又叫游标(Cursor)模式,是对象的行为模式。迭代子模式可以顺序地访问一个聚集中的元素而不必暴漏聚集的内部表象。
一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。我们看下关系图:

角色
抽象迭代子(Iterator)角色:此抽象角色定义出遍历元素所需的接口。
具体迭代子(MyIterator)角色:此角色实现了Iterator接口,并保持迭代过程中的游标位置。
聚集(Collection)角色:此抽象角色给出创建迭代子(Iterator)对象的接口。
具体聚集(MyCollection)角色:实现了创建迭代子(Iterator)对象的接口,返回一个合适的具体迭代子实例。
客户端(Client)角色:持有对聚集及其迭代子对象的引用,调用迭代子对象的迭代接口,也有可能通过迭代子操作聚集元素的增加和删除。

实现代码如下:
抽象迭代子(Iterator)角色:
package com.deppon.tps.module.TestIteratorPattern;public interface Iterator {public Object previous();public Object next();public Boolean hasNext();public Object first();}
具体迭代子(MyIterator)角色:
package com.deppon.tps.module.TestIteratorPattern;public class MyIterator implements Iterator {private Collection collection;private int pos = -1;  public MyIterator(Collection collection){this.collection=collection;}@Overridepublic Object previous() {if(pos>0){pos--;}return collection.get(pos);}@Overridepublic Object next() {if(pos<collection.size()-1){pos++;}return collection.get(pos);}@Overridepublic Boolean hasNext() {if(pos<collection.size()-1){return true;}else{return false;}}@Overridepublic Object first() {pos=0;return collection.get(pos);  }}
抽象聚集角色类
package com.deppon.tps.module.TestIteratorPattern;public interface Collection {public Iterator iterator();public Object get(int i);public int size();}
具体聚集角色类
package com.deppon.tps.module.TestIteratorPattern;public class MyCollection implements Collection {public String[] str = null;  public MyCollection(String[] str){this.str=str;}@Overridepublic Iterator iterator() {   return new MyIterator(this);  }@Overridepublic Object get(int i) {return str[i];  }@Overridepublic int size() {return str.length;  }}
client:
package com.deppon.tps.module.TestIteratorPattern;public class Test { public static void main(String[] args) {String[] str={"A","B","C","D","E","F"};  Collection collection = new MyCollection(str);  Iterator it=collection.iterator();while(it.hasNext()){  System.out.print(it.next());  }}}
测试结果:
ABCDEF
迭代子模式优点
  1. 迭代子模式简化了聚集的接口。迭代子具备了一个遍历接口,这样聚集的接口就不必具备遍历接口。
  2. 每一个聚集对象都可以有一个或多个迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。因此,一个聚集对象可以同时有几个迭代在进行之中。
  3. 由于遍历算法被封装在迭代子角色里面,因此迭代的算法可以独立于聚集角色变化。







0 0