理解设计模式(十六)——迭代器模式

迭代器模式

提出问题

有时候我们想要用多种方式遍历一个数组。比如说:想要跳着遍历一个数组,想要只遍历符合某种条件的元素。还有时候,我们不想返回原始数据,想要对数据做一些处理?

你可能会想到,可以在for循环里面写一个if语句,for循环里再处理。但是如果好多地方都要用到呢?代码冗余是不是太高了?怎么解决?

解决问题

当然是封装啦。你可以把for循环封装成一个函数,然后到处调用。你可以把不同的遍历方式封装成多个不同的函数。再高级一点,封装成一个类,提供各种访问方法。这就是迭代器模式。

上代码:

class List {
constructor() {
this.list = [];
}

add(item) {
// ...
}

remove(item) {
// ...
}

getIterator() {
// 普通迭代器
return new NormalIterator(this.list);
}
getFilterIterator() {
// 过滤迭代器
return new FilterIterator(this.list)
}
}

class NormalIterator {
constructor(list) {
this.list = list;
}
previous() {
// ...
}
next() {
// ...
}
hasNext() {
// ...
}
}

class FilterIterator {
constructor(list) {
this.list = list;
}
previous() {
// 做一些过滤
// ...
}
next() {
// 做一些过滤
// ...
}
hasNext() {
// ...
}
}

let list = new List();
list.add(1);
list.add(2);

let iterator = list.getNormalIterator();
while(iterator.hasNext()) {
// ...
}

iterator = list.getFilterIterator();
while(iterator.hasNext()) {
// ...
}
Author: LeoB_O
Link: https://leob-o.github.io/2019/06/13/IteratorPattern/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.