1
- using System ;
1
+ // EN: Iterator Design Pattern
2
+ //
3
+ // Intent: Provide a way to traverse the elements of an aggregate object without
4
+ // exposing its underlying representation.
5
+ //
6
+ // RU: Паттерн Итератор
7
+ //
8
+ // Назначение: Предоставляет возможность обходить элементы составного объекта,
9
+ // не раскрывая его внутреннего представления.
10
+
11
+ using System ;
2
12
using System . Collections ;
3
13
using System . Collections . Generic ;
4
14
5
15
namespace RefactoringGuru . DesignPatterns . Iterator . Conceptual
6
16
{
7
- class Program
8
- {
9
- public static void Main ( )
10
- {
11
- Client client = new Client ( ) ;
12
- client . ClientCode ( ) ;
13
- }
14
- }
15
-
16
- public class Client
17
- {
18
- public void ClientCode ( )
19
- {
20
- var collection = new WordsCollection ( ) ;
21
- collection . AddItem ( "First" ) ;
22
- collection . AddItem ( "Second" ) ;
23
- collection . AddItem ( "Third" ) ;
24
-
25
- Console . WriteLine ( "Straight traversal:" ) ;
26
-
27
- foreach ( var element in collection )
28
- {
29
- Console . WriteLine ( element ) ;
30
- }
31
-
32
- Console . WriteLine ( "\n Reverse traversal:" ) ;
33
-
34
- collection . ReverseDirection ( ) ;
35
-
36
- foreach ( var element in collection )
37
- {
38
- Console . WriteLine ( element ) ;
39
- }
40
- }
41
- }
42
-
43
17
abstract class Iterator : IEnumerator
44
18
{
45
19
object IEnumerator . Current => Current ( ) ;
46
20
21
+ // EN: Returns the key of the current element
22
+ //
23
+ // RU: Возвращает ключ текущего элемента
47
24
public abstract int Key ( ) ;
48
25
26
+ // EN: Returns the current element
27
+ //
28
+ // RU: Возвращает текущий элемент.
49
29
public abstract object Current ( ) ;
50
30
31
+ // EN: Move forward to next element
32
+ //
33
+ // RU: Переходит к следующему элементу.
51
34
public abstract bool MoveNext ( ) ;
52
35
36
+ // EN: Rewinds the Iterator to the first element
37
+ //
38
+ // RU: Перематывает Итератор к первому элементу.
53
39
public abstract void Reset ( ) ;
54
40
}
55
41
56
42
abstract class IteratorAggregate : IEnumerable
57
43
{
44
+ // EN: Returns an Iterator or another IteratorAggregate for the implementing object.
45
+ //
46
+ // RU: Возвращает Iterator или другой IteratorAggregate для реализующего объекта.
58
47
public abstract IEnumerator GetEnumerator ( ) ;
59
48
}
60
49
50
+ // EN: Concrete Iterators implement various traversal algorithms. These classes
51
+ // store the current traversal position at all times.
52
+ //
53
+ // RU: Конкретные Итераторы реализуют различные алгоритмы обхода. Эти классы
54
+ // постоянно хранят текущее положение обхода.
61
55
class AlphabeticalOrderIterator : Iterator
62
56
{
63
57
private WordsCollection _collection ;
64
58
59
+ // EN: Stores the current traversal position. An iterator may have
60
+ // a lot of other fields for storing iteration state, especially when it is
61
+ // supposed to work with a particular kind of collection.
62
+ //
63
+ // RU: Хранит текущее положение обхода. У итератора может быть
64
+ // множество других полей для хранения состояния итерации, особенно когда он
65
+ // должен работать с определённым типом коллекции.
65
66
private int _position = - 1 ;
66
67
67
68
private bool _reverse = false ;
@@ -100,7 +101,6 @@ public override bool MoveNext()
100
101
{
101
102
return false ;
102
103
}
103
-
104
104
}
105
105
106
106
public override void Reset ( )
@@ -109,6 +109,11 @@ public override void Reset()
109
109
}
110
110
}
111
111
112
+ // EN: Concrete Collections provide one or several methods for retrieving fresh
113
+ // iterator instances, compatible with the collection class.
114
+ //
115
+ // RU: Конкретные Коллекции предоставляют один или несколько методов для
116
+ // получения новых экземпляров итератора, совместимых с классом коллекции.
112
117
class WordsCollection : IteratorAggregate
113
118
{
114
119
List < string > _collection = new List < string > ( ) ;
@@ -135,4 +140,47 @@ public override IEnumerator GetEnumerator()
135
140
return new AlphabeticalOrderIterator ( this , _direction ) ;
136
141
}
137
142
}
143
+
144
+ public class Client
145
+ {
146
+ public void ClientCode ( )
147
+ {
148
+ // EN: The client code may or may not know about the Concrete Iterator or
149
+ // Collection classes, depending on the level of indirection you want to keep in
150
+ // your program.
151
+ //
152
+ // RU: Клиентский код может знать или не знать о Конкретном Итераторе или
153
+ // классах Коллекций, в зависимости от уровня косвенности, который вы хотите
154
+ // сохранить в своей программе.
155
+ var collection = new WordsCollection ( ) ;
156
+ collection . AddItem ( "First" ) ;
157
+ collection . AddItem ( "Second" ) ;
158
+ collection . AddItem ( "Third" ) ;
159
+
160
+ Console . WriteLine ( "Straight traversal:" ) ;
161
+
162
+ foreach ( var element in collection )
163
+ {
164
+ Console . WriteLine ( element ) ;
165
+ }
166
+
167
+ Console . WriteLine ( "\n Reverse traversal:" ) ;
168
+
169
+ collection . ReverseDirection ( ) ;
170
+
171
+ foreach ( var element in collection )
172
+ {
173
+ Console . WriteLine ( element ) ;
174
+ }
175
+ }
176
+ }
177
+
178
+ class Program
179
+ {
180
+ public static void Main ( )
181
+ {
182
+ Client client = new Client ( ) ;
183
+ client . ClientCode ( ) ;
184
+ }
185
+ }
138
186
}
0 commit comments