-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator design pattern.cpp
More file actions
72 lines (60 loc) · 1.37 KB
/
Copy pathiterator design pattern.cpp
File metadata and controls
72 lines (60 loc) · 1.37 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
#include <iostream>
#include <vector>
using namespace std;
// Iterator Interface
class Iterator {
public:
virtual int next() = 0;
virtual bool hasNext() const = 0;
virtual ~Iterator() = default;
};
// Concrete Iterator
class ConcreteIterator : public Iterator {
private:
const vector<int>& collection;
size_t index;
public:
ConcreteIterator(const vector<int>& collection) : collection(collection) {
index = 0;
}
int next() override {
return collection[index++];
}
bool hasNext() const override {
return index < collection.size();
}
};
// Aggregate Interface
class Aggregate {
public:
virtual Iterator* createIterator() const = 0;
virtual ~Aggregate() = default;
};
// Concrete Aggregate
class ConcreteAggregate : public Aggregate {
private:
vector<int> collection;
public:
void add(int item) {
collection.push_back(item);
}
Iterator* createIterator() const override {
return new ConcreteIterator(collection);
}
};
// Client code
int main() {
ConcreteAggregate aggregate;
aggregate.add(1);
aggregate.add(2);
aggregate.add(3);
aggregate.add(4);
aggregate.add(5);
Iterator* iterator = aggregate.createIterator();
while (iterator->hasNext()) {
cout << iterator->next() << " ";
}
cout << endl;
delete iterator;
return 0;
}