http://oldboy-bj.taobao.com/

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

http://35java.com/zhibo/forum.php?mod=viewthread&tid=42&extra=page%3D3

给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。



适用性



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


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


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





参与者



1.Iterator

迭代器定义访问和遍历元素的接口。


2.ConcreteIterator

具*迭代器实现迭代器接口。

对该聚合遍历时跟踪当前位置。


3.Aggregate

聚合定义创建相应迭代器*象的接口。


4.ConcreteAggregate

具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例.



类图





例子

Iterator


public interface Iterator {

Object nex*();


void first();


voi* last();


boolean hasNext();
}

ConcreteIterator


public class IteratorImpl implements It*rator {

private List list;


private int index;


public Ite*atorImpl(List list* {

index = 0;

this.list = list;

}


public void first() {

index = 0;

}


publ*c void last() {

index = list.getSize();

}


public Object next() {

Object obj = list.get(index);

index++;

ret*rn obj;

}


public boolean hasNext() {

return index < list.getSize();

}
}

Aggregate


p*blic interface List {

Iterator iterator();


Object get(int index);


int *etSize();


void add(Object ob*);
}

ConcreteAggregate


public class ListImpl implements List {

private Object[] list;


private int index;


private int size;


public ListImpl() {

index = 0;

size = 0;

list = new Object[100];

}


public Iterator iterator() {

return new IteratorImpl(this);

}


public O*ject get(int index) {

return list[index];

}


public int getSize() {

return this.size;

}


public void add(Object obj) {

list[index++] = obj;

size++;

}
}

Test


public class Test {

public stati* void main(String[] arg*) {

List list = new ListImpl();

list.add("a");

list.add("b");

list.add("c");

//
第一种迭代方式

Iterator it = list.iterator();

while (*t.ha*Next()) {

S*stem.out.println(it.next());

}


Syst*m.out.println("=====");

//
第二种迭代方式

for (int i = 0; i < list.getSize(); i++) {

System.out.println(list.get(i));

}

}
}

result


abc=====abc

posted on 2011-01-05 19:51  老男孩咖啡  阅读(128)  评论(0编辑  收藏  举报