这是我参与11月更文挑战的第20天,活动详情查看:2021最后一次更文挑战
迭代器模式
提供一个对象来顺序访问聚合对象中的一序列数据,而不暴露聚合对象的内部表示。迭代器模式是一种对象行为型模式。
模式结构
- 抽象迭代器:接口声明一个或多个方法来获取与集合兼容的迭代器。 请注意, 返回方法的类型必须被声明为迭代器接口, 因此具体集合可以返回各种不同种类的迭代器。
- 具体迭代器:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。
- 抽象聚合:接口声明了遍历集合所需的操作: 获取下一个元素、 获取当前位置和重新开始迭代等。
- 具体聚合: 实现遍历集合的一种特定算法。 迭代器对象必须跟踪自身遍历的进度。 这使得多个迭代器可以相互独立地遍历同一集合。
// main函数
(()=>{
const con = new ConcreteAggregate();
con.add("first");
con.add("second");
con.add("third");
const iterator = con.getIterator();
if(iterator.hasNext()) {
console.log(iterator);
con.remove(iterator);
}
})()
//抽象聚合
interface Aggregate {
add(obj: any):void;
remove(obj: any): void;
getIterator(): Iterator<string>;
}
//具体聚合
class ConcreteAggregate implements Aggregate {
private list: any[] = [];
add( obj: any) {
this.list.push(obj);
}
remove( obj: any) {
let newList:any[] = []
this.list.forEach((value)=>{
if(value != obj){
newList.push(value)
}
})
this.list = newList;
}
public getIterator(): Iterator<string> {
return (new ConcreteIterator(this.list));
}
}
//抽象迭代器
interface Iterator<T> {
first():T;
next(): T;
hasNext():boolean;
}
//具体迭代器
class ConcreteIterator implements Iterator<string> {
private list: any = null;
private index = -1;
constructor(list:any){
this.list = list;
}
public hasNext():boolean {
if (this.index < this.list.length - 1) {
return true;
} else {
return false;
}
}
public first() {
this.index = 0;
const obj = this.list.get(this.index);
;
return obj;
}
public next() {
let obj:any = null;
if (this.hasNext()) {
obj = this.list.get(++this.index);
}
return obj;
}
}
复制代码
主要优点
- 它支持以不同方式遍历一个聚合,甚至可以自定义迭代器的子类以支持新的遍历。
- 增加新的聚合类和迭代器类都很方便,无须修改原有代码。
- 封装性良好,为遍历不同的聚合结构提供一个统一的接口。
适用场景
- 当集合背后为复杂的数据结构,且你希望对客户端隐藏其复杂性时,可使用迭代器模式,即当访问一个聚合对象的内容而无须暴露其内部细节的表示时。
- 使用该模式可以减少程序中重复的遍历代码,通过此模式可为聚合对象提供多种遍历方式时。
- 若希望代码能够遍历不同的甚至是无法预知的数据结构,可使用迭代器模式,为遍历不同的聚合结构提供一个统一的接口时。
- \