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等采用同样的接口遍历。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值