【设计模式】行为型模式-Iterator模式
# 功能
提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示
# 解决
- 主要解决:不同的方式来遍历整个整合对象
- 何时使用:遍历一个聚合对象
- 如何解决:把在元素之间游走的责任交给迭代器,而不是聚合对象
- 关键代码:定义接口:hasNext, next
# 优缺点
- 优点:
- 它支持以不同的方式遍历一个聚合对象
- 迭代器简化了聚合类
- 在同一个聚合上可以有多个遍历
- 在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码
- 缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性
# 应用场景
- 应用实例:JAVA 中的 iterator
- 使用场景:
- 访问一个聚合对象的内容而无须暴露它的内部表示
- 需要为聚合对象提供多种遍历方式
- 为遍历不同的聚合结构提供一个统一的接口
- 注意事项:迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据
# 简单示例代码部分
Iterator.h
#ifndef _ITERATOR_H_
#define _ITERATOR_H_
#include <iostream>
using namespace std;
class Aggregate;
typedef int Object;
class Iterator
{
public:
virtual ~Iterator(){}
virtual void First() = 0;
virtual void Next() = 0;
virtual bool IsDone() = 0;
virtual Object CurrentItem() = 0;
protected:
Iterator(){}
};
class ConcreteIterator:public Iterator {
public:
ConcreteIterator(Aggregate* ag , int idx = 0){
this->_ag = ag;
this->_idx = idx;
}
~ConcreteIterator(){}
void First(){
_idx = 0;
}
void Next();
bool IsDone();
Object CurrentItem();
private:
Aggregate* _ag;
int _idx;
};
class Aggregate
{
public:
virtual ~Aggregate(){}
virtual Iterator* CreateIterator() = 0;
virtual Object GetItem(int idx) = 0;
virtual int GetSize() = 0;
protected:
Aggregate(){}
};
class ConcreteAggregate:public Aggregate {
public:
enum {SIZE = 3};
ConcreteAggregate(){
for (int i = 0; i < SIZE; i++)
_objs[i] = i;
}
~ConcreteAggregate(){}
Iterator* CreateIterator(){
return new ConcreteIterator(this);
}
Object GetItem(int idx){
if (idx < this->GetSize())
return _objs[idx];
else
return -1;
}
int GetSize(){
return SIZE;
}
private:
Object _objs[SIZE];
};
void ConcreteIterator::Next() {
if (_idx < _ag->GetSize())
_idx++;
}
bool ConcreteIterator::IsDone() {
return (_idx == _ag->GetSize());
}
Object ConcreteIterator::CurrentItem() {
return _ag->GetItem(_idx);
}
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
main.cpp
#include "Iterator.h"
#include <iostream>
using namespace std;
int main() {
Aggregate* ag = new ConcreteAggregate();
Iterator* it = new ConcreteIterator(ag);
for (; !(it->IsDone()) ; it->Next()) {
cout<<it->CurrentItem()<<endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2022/05/18, 15:47:37