面向对象设计模式:行为型模式之迭代器模式

一、迭代器模式,Iterator Pattern

aka:Cursor Pattern

1.1 Intent 意图

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
提供一种按顺序访问聚合对象的元素而不公开其基础表示形式的方法。

1.2 Motivation 动机
  • An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. 聚合对象(如列表)应该提供一种访问其元素而不公开其内部结构的方法.
  • The key idea in iterator pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object. 迭代器模式中的关键思想是将访问和遍历的责任从列表对象中取出,并将其放入迭代器对象中.
  • Separating the traversal mechanism from the List object lets us define iterators for different traversal policies without enumerating them in the List interface. 将遍历机制与 List 对象分开,使我们可以为不同的遍历策略定义迭代器,而无需在List 接口中枚举它们.
1.3 Applicability 适用性
  • To access an aggregate object’s contents without exposing its internal representation. 要访问聚合对象的内容而不公开其内部表示形式.
  • To support multiple traversals of aggregate objects. 以支持聚合对象的多次遍历.
  • To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration). 提供遍历不同聚合结构的统一接口(即支持多态迭代).
1.4 迭代器模式类图

在这里插入图片描述

  • ConcreteIterator 定义在哪?

    • Public Iterator: Concrete iterator is defined as a class independent from aggregate. 定义为独立于聚合类的类-外部迭代器类
    • Private Iterator: Concrete iterator is defined as a inner class in the aggregate. 定义为在聚合类内部的类-内部私有迭代器类
  • 谁控制迭代?

    • Active Iterator (External Iterator): The client controls the iteration
      在这里插入图片描述
    • Passive Iterator (Internal Iterator): The iterator controls the iteration
      在这里插入图片描述
  • Who defines the traversal algorithm

    • The aggregate might define the traversal algorithm and use the iterator to store just the state of the iteration (cursor), it points to the current position in the aggregate
    • The iterator is responsible for the traversal algorithm, then it’s easy to use different iteration algorithms on the same aggregate, and it can also be easier to reuse the same algorithm on different aggregates.
1.5 迭代器鲁棒性
  • How robust is the iterator? 迭代器鲁棒性如何?

    • It can be dangerous to modify an aggregate while you’re traversing it.
    • Copied Iterator
      • A simple solution is to copy the aggregate and traverse the copy, but that’s too expensive to do in general.
    • Robust iterator
      • Ensures that insertions and removals won’t affect traversal, and it does it without copying the aggregate. On insertion or removal, the aggregate either adjusts the internal state of iterators it has produced, or it maintains information internally to ensure proper traversal.
  • Static Iterator and Dynamic Iterator:静态迭代器和动态迭代器

    • Static Iterator: A copied iterator which contains a snapshot of the aggregate when iterator is created. New changes are invisible to the traversal approach.
    • Dynamic Iterator: Dynamic Iterator is opposited to the static one. Any changes to the aggregate are allowed and available when traversing the aggregate. Completely Dynamic Iterator is not easy to be implemented.
  • Fail-Fast in Java:Java 中的快速失败

    • Fail-fast is a property of a system or module with respect to its response to failures. 快速故障是系统或模块关于其对故障响应的一个特性.
    • A fail-fast system is designed to immediately report at its interface any failure or condition that is likely to lead to failure.
    • Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process.
    • Fail-fast Iterator throws an exception when the aggregate is changed during iteration.
    • Fail-fast 与 并发修改异常 ConcurrentModificationException
import java.util.ArrayList;
import java.util.Iterator;

public class FailFastTest {

	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("haha");
		arrayList.add("hehe");
		arrayList.add("xixi");
		
		Iterator<String> iterator = arrayList.iterator();
		
		//create a new thread to traverse using iterator.	
		new Thread(){
			public void run() {
				while(iterator.hasNext()){
					System.out.println(iterator.next());
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		//main thread try to change the aggregate: 
		//Fail-fast Iterator throws an exception
		try {
			Thread.sleep(1500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		arrayList.add("wawa");
	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值