Skip to content

Commit b8cc2ac

Browse files
committed
Iterator: improve conceptual example
1 parent 76152d3 commit b8cc2ac

File tree

1 file changed

+86
-38
lines changed

1 file changed

+86
-38
lines changed

Iterator.Conceptual/Program.cs

Lines changed: 86 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,68 @@
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;
212
using System.Collections;
313
using System.Collections.Generic;
414

515
namespace RefactoringGuru.DesignPatterns.Iterator.Conceptual
616
{
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("\nReverse traversal:");
33-
34-
collection.ReverseDirection();
35-
36-
foreach (var element in collection)
37-
{
38-
Console.WriteLine(element);
39-
}
40-
}
41-
}
42-
4317
abstract class Iterator : IEnumerator
4418
{
4519
object IEnumerator.Current => Current();
4620

21+
// EN: Returns the key of the current element
22+
//
23+
// RU: Возвращает ключ текущего элемента
4724
public abstract int Key();
4825

26+
// EN: Returns the current element
27+
//
28+
// RU: Возвращает текущий элемент.
4929
public abstract object Current();
5030

31+
// EN: Move forward to next element
32+
//
33+
// RU: Переходит к следующему элементу.
5134
public abstract bool MoveNext();
5235

36+
// EN: Rewinds the Iterator to the first element
37+
//
38+
// RU: Перематывает Итератор к первому элементу.
5339
public abstract void Reset();
5440
}
5541

5642
abstract class IteratorAggregate : IEnumerable
5743
{
44+
// EN: Returns an Iterator or another IteratorAggregate for the implementing object.
45+
//
46+
// RU: Возвращает Iterator или другой IteratorAggregate для реализующего объекта.
5847
public abstract IEnumerator GetEnumerator();
5948
}
6049

50+
// EN: Concrete Iterators implement various traversal algorithms. These classes
51+
// store the current traversal position at all times.
52+
//
53+
// RU: Конкретные Итераторы реализуют различные алгоритмы обхода. Эти классы
54+
// постоянно хранят текущее положение обхода.
6155
class AlphabeticalOrderIterator : Iterator
6256
{
6357
private WordsCollection _collection;
6458

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+
// должен работать с определённым типом коллекции.
6566
private int _position = -1;
6667

6768
private bool _reverse = false;
@@ -100,7 +101,6 @@ public override bool MoveNext()
100101
{
101102
return false;
102103
}
103-
104104
}
105105

106106
public override void Reset()
@@ -109,6 +109,11 @@ public override void Reset()
109109
}
110110
}
111111

112+
// EN: Concrete Collections provide one or several methods for retrieving fresh
113+
// iterator instances, compatible with the collection class.
114+
//
115+
// RU: Конкретные Коллекции предоставляют один или несколько методов для
116+
// получения новых экземпляров итератора, совместимых с классом коллекции.
112117
class WordsCollection : IteratorAggregate
113118
{
114119
List<string> _collection = new List<string>();
@@ -135,4 +140,47 @@ public override IEnumerator GetEnumerator()
135140
return new AlphabeticalOrderIterator(this, _direction);
136141
}
137142
}
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("\nReverse 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+
}
138186
}

0 commit comments

Comments
 (0)