-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwords_example.dart
85 lines (71 loc) · 2.02 KB
/
words_example.dart
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
// https://refactoring.guru/design-patterns/iterator/swift/example#example-0
/// This example illustrates the structure of the Iterator design pattern
/// and focuses on the following questions:
///
/// What classes does it consist of?
/// What roles do these classes play?
/// In what way the elements of the pattern are related?
///
///
/// After learning about the pattern’s structure it’ll be easier for you to grasp the following example,
///
/// based on a real-world Swift use case.
library;
/// This is a collection that we're going to iterate through using an iterator
/// derived from IteratorProtocol.
abstract interface class Collection<T> {
final List<T> items = [];
void append(T item);
Iterator<T> makeIterator();
}
abstract interface class Iterator<T> {
const Iterator();
T? next();
}
class WordsCollection implements Collection<String> {
@override
final List<String> items = [];
@override
void append(String item) {
items.add(item);
}
@override
WordsIterator makeIterator() {
return WordsIterator(this);
}
}
/// Concrete Iterators implement various traversal algorithms. These classes
/// store the current traversal position at all times.
class WordsIterator implements Iterator<String> {
final WordsCollection collection;
int index = 0;
WordsIterator(this.collection);
@override
String? next() {
index += 1;
return index < collection.items.length ? collection.items[index] : null;
}
}
/// Client does not know the internal representation of a given sequence.
class Client {
static void clientCode({required Collection collection}) {
for (final item in collection.items) {
print(item);
}
}
}
/// Let's see how it all works together.
void main() {
final words = WordsCollection();
words.append("First");
words.append("Second");
words.append("Third");
print("Straight traversal using IteratorProtocol:");
Client.clientCode(collection: words);
}
// Output:
// Execution result
// Straight traversal using IteratorProtocol:
// First
// Second
// Third