Iterator Pattern 迭代器模式

Iterator Pattern: provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

It also places the task of traversal on the iterator object, not on the aggregate which simplifies the aggregate interface and implementation, and places the reponsibility where it should be.

Iterator模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明的访问集合内部的数据。提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示

迭代器可以遍历各种Collection。注意的是Hashtable是key和value,遍历value时用values.iterator(). 

实现Iterator接口:

public class IteratorTest implements Iterator{

	@Override
	public boolean hasNext() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Object next() {
		// TODO Auto-generated method stub
		return null;
	}
}
定义Client:

public class Test {
	public void main(String[] args) {
		Iterator it = new IteratorTest();
		while(it.hasNext()) {
			// do something
		}
	}
}
Design Principle:

Single Responsibility: A class should have only one reason to change.

Every responsibility of a class is an area of potential change. More than one responsibility means more than one area of change.
应用:对Array, ArrayList, Hashtable等采用同样的接口遍历。


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Geurney/article/details/46785529
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭