来自于《大话设计模式》
迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
UML 类图:
代码实现 C++:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Aggregate
6 {
7 private:
8 string data[100];
9 int index;
10 public:
11 Aggregate() : index(0){}
12 void push_back(const string& s)
13 {
14 data[index++] = s;
15 }
16 void push_pop()
17 {
18 --index;
19 }
20 string* getData()
21 {
22 return data;
23 }
24 int size()
25 {
26 return index;
27 }
28 };
29
30 class Iterator
31 {
32 private:
33 Aggregate* pAggr;
34 int current;
35 public:
36 Iterator(Aggregate& aggr)
37 {
38 pAggr = &aggr;
39 current = 0;
40 }
41 string First()
42 {
43 if (pAggr->size() > 0)
44 {
45 return (pAggr->getData())[0];
46 }
47 else
48 {
49 return "";
50 }
51 }
52 string End()
53 {
54 if (pAggr->size() > 0)
55 {
56 return (pAggr->getData())[pAggr->size() - 1];
57 }
58 else
59 {
60 return "";
61 }
62 }
63 void Next()
64 {
65 ++current;
66 }
67 bool IsDone()
68 {
69 return current == pAggr->size();
70 }
71 string CurrentItem()
72 {
73 if (pAggr->size() > 0)
74 {
75 return (pAggr->getData())[current];
76 }
77 else
78 {
79 return "";
80 }
81 }
82 void setBegin()
83 {
84 current = 0;
85 }
86 void setEnd()
87 {
88 current = pAggr->size();
89 }
90
91 void setRBegin()
92 {
93 current = pAggr->size() - 1;
94 }
95 void setREnd()
96 {
97 current = -1;
98 }
99 bool IsRDone()
100 {
101 return current == -1;
102 }
103 void RNext()
104 {
105 --current;
106 }
107 };
108
109 int main()
110 {
111 Aggregate aggr;
112 aggr.push_back("a");
113 aggr.push_back("b");
114 aggr.push_back("c");
115 aggr.push_back("d");
116 aggr.push_back("e");
117
118 Iterator iter(aggr);
119
120 while (!iter.IsDone())
121 {
122 cout << iter.CurrentItem() << ", hello!" << endl;
123 iter.Next();
124 }
125
126 iter.setBegin();
127 while (!iter.IsDone())
128 {
129 cout << iter.CurrentItem() << ", bye!" << endl;
130 iter.Next();
131 }
132
133
134 iter.setRBegin();
135 while (!iter.IsRDone())
136 {
137 cout << iter.CurrentItem() << ", reverse!" << endl;
138 iter.RNext();
139 }
140
141 iter.setBegin();
142
143 return 0;
144 }
posted on 2011-04-29 16:52
unixfy 阅读(216)
评论(0) 编辑 收藏 引用