-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathiterator.cpp
More file actions
88 lines (77 loc) · 1.62 KB
/
Copy pathiterator.cpp
File metadata and controls
88 lines (77 loc) · 1.62 KB
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
/*!
* \brief Iterator. Provide a way to access the elements of
* an aggregate Object sequentially without exposing its
* underlying representation.
*
* client -> Iterator -> Aggregate -> Object
* | |
* ConcreteIterator ConcreteAggregate
*/
#include <iostream>
#include <vector>
class Object {
public:
Object(int value) : value_(value) {};
void Excute() {
std::cout << value_ << std::endl;
}
private:
int value_;
};
class Aggregate {
public:
virtual void add(Object &obj) = 0;
virtual Object& operator[](int index) = 0;
virtual int size() = 0;
};
class ConcreteAggregate : public Aggregate {
public:
void add(Object &obj) {
objects_.push_back(obj);
}
int size() {
return objects_.size();
}
Object& operator[](int index) {
return objects_[index];
}
private:
std::vector<Object> objects_;
};
class Iterator {
public:
virtual void next() = 0;
virtual bool has_next() = 0;
};
class ConcreteIterator :public Iterator {
public:
ConcreteIterator(Aggregate *agg) {
this->agg_ = agg;
index_ = 0;
}
void next() {
(*agg_)[index_++].Excute();
}
bool has_next() {
return (index_ < agg_->size());
}
public:
Aggregate *agg_;
int index_;
};
int main() {
Aggregate *objects = new ConcreteAggregate();
Object a(1), b(2), c(3);
objects->add(a);
objects->add(b);
objects->add(c);
Iterator *iter = new ConcreteIterator(objects);
while (iter->has_next()) {
iter->next();
}
std::cout << "Finish." << std::endl;
delete objects;
delete iter;
system("pause");
return 0;
}