您的位置:首页 > 其它

迭代器模式(Iterator Pattern)

2016-11-28 14:24 351 查看

1. 迭代器模式定义

提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。



适用性:

访问一个聚合对象的内容而无需暴露它的内部表示。

支持对聚合对象的多种遍历。

为遍历不同的聚合结构提供一个统一的接口(即, 支持多态迭代)。

类图:



2. 实例

//测试
public class IteratorPatternTest {
public static void main(String[] args){
Collection collection=new MyCollection();
Iterator iterator=collection.createIterator();
while(iterator.hasNext()){
String s=iterator.next().toString();
System.out.println(s);
}

}
}

//集合接口
interface Collection{
public Iterator createIterator();

public Object get(int pos);
public int size();
}

//集合接口的实现类
class MyCollection implements Collection{
private String str[]={"a","b","c","d","e","f"};

@Override
public Iterator createIterator(){
return new MyIterator(this);
}

@Override
public Object get(int pos){
return str[pos];
}

@Override
public int size(){
return str.length;
}
}

//迭代器接口
interface Iterator{
public boolean hasNext();
public Object next();
//public void remove();
}

//迭代器接口的实现类
class MyIterator implements Iterator{
private Collection collection=null;
private int pos=-1;

public MyIterator(Collection collection){
this.collection=collection;
}

@Override
public boolean hasNext(){
if(pos<collection.size()-1){
return true;
}
return false;
}

@Override
public Object next(){
if(hasNext()){
pos++;
}
return collection.get(pos);
}
}


运行结果:

a
b
c
d
e
f
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: