一、简介
1、迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
2、类成员
(1)Iterator(迭代器)迭代器定义访问和遍历元素的接口
(2)ConcreteIterator (具体迭代器)具体迭代器实现迭代器接口对该聚合遍历时跟踪当前位置
(3)Aggregate (聚合)聚合定义创建相应迭代器对象的接口
(4)ConcreteAggregate (具体聚合)具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例
3、现在的高级语言如C#,JAVA等本身已经将这个模式做在语言中了,所以这里只是学习一下思路而已。
4、UML
5、所属类别:行为型
二、C++代码
1 // 迭代器模式.cpp : 定义控制台应用程序的入口点。
2 //
3
4 #include "stdafx.h"
5 #include<iostream>
6 #include<string>
7 #include<vector>
8 using namespace std;
9
10 class Iterator
11 {
12 public:
13 Iterator(){}
14 virtual ~Iterator(){}
15 virtual string first()=0;
16 virtual void next()=0;
17 virtual bool isdone()=0;
18 virtual string currentitem()=0;
19 };
20 class Aggregate
21 {
22 public:
23 Aggregate(){}
24 virtual ~Aggregate(){}
25 //virtual Iterator* createiterator()=0;
26 };
27
28 class ConcreteAggregate:public Aggregate
29 {
30 private:
31 vector<string>Vector;
32 public:
33 ConcreteAggregate(){}
34 virtual ~ConcreteAggregate(){}
35 int count()
36 {
37 return Vector.size();
38 }
39 void add(string s)
40 {
41 Vector.push_back(s);
42 }
43 string value(int index)
44 {
45 if (index<Vector.size())
46 {
47 return Vector[index];
48 }
49 }
50 };
51 class ConcreteIterator:public Iterator
52 {
53 private:
54 ConcreteAggregate * myConcreteAggregate;
55 int count;
56 public:
57 ConcreteIterator(ConcreteAggregate *c):myConcreteAggregate(c)
58 {
59 count=0;
60 }
61 virtual ~ConcreteIterator(){}
62 virtual string first()
63 {
64 count=0;
65 return myConcreteAggregate->value(0);
66 }
67 virtual void next()
68 {
69 if(count<myConcreteAggregate->count())
70 {
71 count++;
72 //return myConcreteAggregate->value(count);
73 }
74 }
75 virtual bool isdone()
76 {
77 return count<myConcreteAggregate->count() ? true : false;
78 }
79 virtual string currentitem()
80 {
81 return myConcreteAggregate->value(count);
82 }
83 };
84 int _tmain(int argc, _TCHAR* argv[])
85 {
86 ConcreteAggregate *c=new ConcreteAggregate();
87 c->add("hello");
88 c->add(" ");
89 c->add("world");
90 c->add("!");
91 ConcreteIterator *iter=new ConcreteIterator(c);
92 for(iter->first();iter->isdone();iter->next())
93 {
94 cout<<iter->currentitem();
95 }
96 return 0;
97 }