Skip to content

Commit 8b13a95

Browse files
committed
Various improvements
1 parent b8cc2ac commit 8b13a95

File tree

15 files changed

+218
-196
lines changed

15 files changed

+218
-196
lines changed

Adapter.Conceptual/Program.cs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,24 @@
1313

1414
namespace RefactoringGuru.DesignPatterns.Adapter.Conceptual
1515
{
16-
// EN: The Target defines the domain-specific interface used by the client code.
16+
// EN: The Target defines the domain-specific interface used by the client
17+
// code.
1718
//
18-
// RU: Целевой класс объявляет интерфейс, с которым может работать клиентский
19-
// код.
19+
// RU: Целевой класс объявляет интерфейс, с которым может работать
20+
// клиентский код.
2021
interface ITarget
2122
{
2223
string GetRequest();
2324
}
2425

2526
// EN: The Adaptee contains some useful behavior, but its interface is
26-
// incompatible with the existing client code. The Adaptee needs some adaptation
27-
// before the client code can use it.
27+
// incompatible with the existing client code. The Adaptee needs some
28+
// adaptation before the client code can use it.
2829
//
2930
// RU: Адаптируемый класс содержит некоторое полезное поведение, но его
30-
// интерфейс несовместим с существующим клиентским кодом. Адаптируемый класс
31-
// нуждается в некоторой доработке, прежде чем клиентский код сможет его
32-
// использовать.
31+
// интерфейс несовместим с существующим клиентским кодом. Адаптируемый
32+
// класс нуждается в некоторой доработке, прежде чем клиентский код сможет
33+
// его использовать.
3334
class Adaptee
3435
{
3536
public string GetSpecificRequest()
@@ -38,8 +39,8 @@ public string GetSpecificRequest()
3839
}
3940
}
4041

41-
// EN: The Adapter makes the Adaptee's interface compatible with the Target's
42-
// interface.
42+
// EN: The Adapter makes the Adaptee's interface compatible with the
43+
// Target's interface.
4344
//
4445
// RU: Адаптер делает интерфейс Адаптируемого класса совместимым с целевым
4546
// интерфейсом.
@@ -49,12 +50,12 @@ class Adapter : ITarget
4950

5051
public Adapter(Adaptee adaptee)
5152
{
52-
_adaptee = adaptee;
53+
this._adaptee = adaptee;
5354
}
5455

5556
public string GetRequest()
5657
{
57-
return $"This is '{_adaptee.GetSpecificRequest()}'";
58+
return $"This is '{this._adaptee.GetSpecificRequest()}'";
5859
}
5960
}
6061

Builder.Conceptual/Program.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ public class Client
195195
// RU: Клиентский код создаёт объект-строитель, передаёт его директору,
196196
// а затем инициирует процесс построения. Конечный результат
197197
// извлекается из объекта-строителя.
198-
public void ClientCode(Director director)
198+
public static void ClientCode(Director director)
199199
{
200200
var builder = new ConcreteBuilder();
201201
director.Builder = builder;
@@ -224,9 +224,7 @@ class Program
224224
{
225225
static void Main(string[] args)
226226
{
227-
var client = new Client();
228-
var director = new Director();
229-
client.ClientCode(director);
227+
Client.ClientCode(new Director());
230228
}
231229
}
232230
}

Decorator.Conceptual/Program.cs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -80,24 +80,24 @@ public override string Operation()
8080
}
8181
}
8282

83-
// EN: Concrete Decorators call the wrapped object and alter its result in some
84-
// way.
83+
// EN: Concrete Decorators call the wrapped object and alter its result in
84+
// some way.
8585
//
86-
// RU: Конкретные Декораторы вызывают обёрнутый объект и изменяют его результат
87-
// некоторым образом.
86+
// RU: Конкретные Декораторы вызывают обёрнутый объект и изменяют его
87+
// результат некоторым образом.
8888
class ConcreteDecoratorA : Decorator
8989
{
9090
public ConcreteDecoratorA(Component comp) : base(comp)
9191
{
9292
}
9393

94-
// EN: Decorators may call parent implementation of the operation, instead
95-
// of calling the wrapped object directly. This approach simplifies
96-
// extension of decorator classes.
94+
// EN: Decorators may call parent implementation of the operation,
95+
// instead of calling the wrapped object directly. This approach
96+
// simplifies extension of decorator classes.
9797
//
98-
// RU: Декораторы могут вызывать родительскую реализацию операции, вместо
99-
// того, чтобы вызвать обёрнутый объект напрямую. Такой подход упрощает
100-
// расширение классов декораторов.
98+
// RU: Декораторы могут вызывать родительскую реализацию операции,
99+
// вместо того, чтобы вызвать обёрнутый объект напрямую. Такой подход
100+
// упрощает расширение классов декораторов.
101101
public override string Operation()
102102
{
103103
return $"ConcreteDecoratorA({base.Operation()})";
@@ -123,13 +123,13 @@ public override string Operation()
123123

124124
public class Client
125125
{
126-
// EN: The client code works with all objects using the Component interface.
127-
// This way it can stay independent of the concrete classes of components it
128-
// works with.
126+
// EN: The client code works with all objects using the Component
127+
// interface. This way it can stay independent of the concrete classes
128+
// of components it works with.
129129
//
130130
// RU: Клиентский код работает со всеми объектами, используя интерфейс
131-
// Компонента. Таким образом, он остаётся независимым от конкретных классов
132-
// компонентов, с которыми работает.
131+
// Компонента. Таким образом, он остаётся независимым от конкретных
132+
// классов компонентов, с которыми работает.
133133
public void ClientCode(Component component)
134134
{
135135
Console.WriteLine("RESULT: " + component.Operation());
@@ -149,13 +149,13 @@ static void Main(string[] args)
149149

150150
// EN: ...as well as decorated ones.
151151
//
152-
// Note how decorators can wrap not only simple components but the other
153-
// decorators as well.
152+
// Note how decorators can wrap not only simple components but the
153+
// other decorators as well.
154154
//
155155
// RU: ...так и декорированные.
156156
//
157-
// Обратите внимание, что декораторы могут обёртывать не только простые
158-
// компоненты, но и другие декораторы.
157+
// Обратите внимание, что декораторы могут обёртывать не только
158+
// простые компоненты, но и другие декораторы.
159159
ConcreteDecoratorA decorator1 = new ConcreteDecoratorA(simple);
160160
ConcreteDecoratorB decorator2 = new ConcreteDecoratorB(decorator1);
161161
Console.WriteLine("Client: Now I've got a decorated component:");

Facade.Conceptual/Program.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ class Client
106106
// интерфейс, предоставляемый Фасадом. Когда фасад управляет жизненным
107107
// циклом подсистемы, клиент может даже не знать о существовании
108108
// подсистемы. Такой подход позволяет держать сложность под контролем.
109-
public void ClientCode(Facade facade)
109+
public static void ClientCode(Facade facade)
110110
{
111111
Console.Write(facade.Operation());
112112
}
@@ -116,8 +116,6 @@ class Program
116116
{
117117
static void Main(string[] args)
118118
{
119-
Client client = new Client();
120-
121119
// EN: The client code may have some of the subsystem's objects
122120
// already created. In this case, it might be worthwhile to
123121
// initialize the Facade with these objects instead of letting the
@@ -130,7 +128,7 @@ static void Main(string[] args)
130128
Subsystem1 subsystem1 = new Subsystem1();
131129
Subsystem2 subsystem2 = new Subsystem2();
132130
Facade facade = new Facade(subsystem1, subsystem2);
133-
client.ClientCode(facade);
131+
Client.ClientCode(facade);
134132
}
135133
}
136134
}

Flyweight.Conceptual/Program.cs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public void Operation(Car uniqueState)
4242
{
4343
string s = JsonConvert.SerializeObject(this._sharedState);
4444
string u = JsonConvert.SerializeObject(uniqueState);
45-
Console.Write($"Flyweight: Displaying shared {s} and unique {u} state.\n");
45+
Console.WriteLine($"Flyweight: Displaying shared {s} and unique {u} state.");
4646
}
4747
}
4848

@@ -100,20 +100,20 @@ public Flyweight GetFlyweight(Car sharedState)
100100

101101
if (flyweights.Where(t => t.Item2 == key).Count() == 0)
102102
{
103-
Console.Write("FlyweightFactory: Can't find a flyweight, creating new one.\n");
103+
Console.WriteLine("FlyweightFactory: Can't find a flyweight, creating new one.");
104104
this.flyweights.Add(new Tuple<Flyweight, string>(new Flyweight(sharedState), key));
105105
}
106106
else
107107
{
108-
Console.Write("FlyweightFactory: Reusing existing flyweight.\n");
108+
Console.WriteLine("FlyweightFactory: Reusing existing flyweight.");
109109
}
110110
return this.flyweights.Where(t => t.Item2 == key).FirstOrDefault().Item1;
111111
}
112112

113113
public void listFlyweights()
114114
{
115115
var count = flyweights.Count;
116-
Console.Write($"\nFlyweightFactory: I have {count} flyweights:\n");
116+
Console.WriteLine($"\nFlyweightFactory: I have {count} flyweights:");
117117
foreach (var flyweight in flyweights)
118118
{
119119
Console.WriteLine(flyweight.Item2);
@@ -138,29 +138,29 @@ public class Client
138138
{
139139
public void addCarToPoliceDatabase(FlyweightFactory factory, Car car)
140140
{
141-
Console.Write("\nClient: Adding a car to database.\n");
141+
Console.WriteLine("\nClient: Adding a car to database.");
142142

143143
var flyweight = factory.GetFlyweight(new Car {
144144
Color = car.Color,
145145
Model = car.Model,
146146
Company = car.Company
147147
});
148148

149-
// EN: The client code either stores or calculates extrinsic state and
150-
// passes it to the flyweight's methods.
149+
// EN: The client code either stores or calculates extrinsic state
150+
// and passes it to the flyweight's methods.
151151
//
152-
// RU: Клиентский код либо сохраняет, либо вычисляет внешнее состояние и
153-
// передает его методам легковеса.
152+
// RU: Клиентский код либо сохраняет, либо вычисляет внешнее
153+
// состояние и передает его методам легковеса.
154154
flyweight.Operation(car);
155155
}
156156

157-
public void ClientCode()
157+
public static void ClientCode()
158158
{
159-
// EN: The client code usually creates a bunch of pre-populated flyweights in
160-
// the initialization stage of the application.
159+
// EN: The client code usually creates a bunch of pre-populated
160+
// flyweights in the initialization stage of the application.
161161
//
162-
// RU: Клиентский код обычно создает кучу предварительно заполненных легковесов
163-
// на этапе инициализации приложения.
162+
// RU: Клиентский код обычно создает кучу предварительно заполненных
163+
// легковесов на этапе инициализации приложения.
164164
var factory = new FlyweightFactory(
165165
new Car { Company = "Chevrolet", Model = "Camaro2018", Color = "pink" },
166166
new Car { Company = "Mercedes Benz", Model = "C300", Color = "black" },
@@ -194,8 +194,7 @@ class Program
194194
{
195195
static void Main(string[] args)
196196
{
197-
Client client = new Client();
198-
client.ClientCode();
197+
Client.ClientCode();
199198
}
200199
}
201200
}

Iterator.Conceptual/Program.cs

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -41,27 +41,29 @@ abstract class Iterator : IEnumerator
4141

4242
abstract class IteratorAggregate : IEnumerable
4343
{
44-
// EN: Returns an Iterator or another IteratorAggregate for the implementing object.
44+
// EN: Returns an Iterator or another IteratorAggregate for the
45+
// implementing object.
4546
//
46-
// RU: Возвращает Iterator или другой IteratorAggregate для реализующего объекта.
47+
// RU: Возвращает Iterator или другой IteratorAggregate для реализующего
48+
// объекта.
4749
public abstract IEnumerator GetEnumerator();
4850
}
4951

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

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+
// EN: Stores the current traversal position. An iterator may have a lot
62+
// of other fields for storing iteration state, especially when it is
6163
// supposed to work with a particular kind of collection.
6264
//
63-
// RU: Хранит текущее положение обхода. У итератора может быть
64-
// множество других полей для хранения состояния итерации, особенно когда он
65+
// RU: Хранит текущее положение обхода. У итератора может быть множество
66+
// других полей для хранения состояния итерации, особенно когда он
6567
// должен работать с определённым типом коллекции.
6668
private int _position = -1;
6769

@@ -74,25 +76,25 @@ public AlphabeticalOrderIterator(WordsCollection collection, bool reverse = fals
7476

7577
if (reverse)
7678
{
77-
_position = collection.getItems().Count;
79+
this._position = collection.getItems().Count;
7880
}
7981
}
8082

8183
public override object Current()
8284
{
83-
return _collection.getItems()[_position];
85+
return this._collection.getItems()[_position];
8486
}
8587

8688
public override int Key()
8789
{
88-
return _position;
90+
return this._position;
8991
}
9092

9193
public override bool MoveNext()
9294
{
9395
int updatedPosition = this._position + (this._reverse ? -1 : 1);
9496

95-
if (updatedPosition >= 0 && updatedPosition < _collection.getItems().Count)
97+
if (updatedPosition >= 0 && updatedPosition < this._collection.getItems().Count)
9698
{
9799
this._position = updatedPosition;
98100
return true;
@@ -109,8 +111,8 @@ public override void Reset()
109111
}
110112
}
111113

112-
// EN: Concrete Collections provide one or several methods for retrieving fresh
113-
// iterator instances, compatible with the collection class.
114+
// EN: Concrete Collections provide one or several methods for retrieving
115+
// fresh iterator instances, compatible with the collection class.
114116
//
115117
// RU: Конкретные Коллекции предоставляют один или несколько методов для
116118
// получения новых экземпляров итератора, совместимых с классом коллекции.
@@ -145,13 +147,13 @@ public class Client
145147
{
146148
public void ClientCode()
147149
{
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.
150+
// EN: The client code may or may not know about the Concrete
151+
// Iterator or Collection classes, depending on the level of
152+
// indirection you want to keep in your program.
151153
//
152-
// RU: Клиентский код может знать или не знать о Конкретном Итераторе или
153-
// классах Коллекций, в зависимости от уровня косвенности, который вы хотите
154-
// сохранить в своей программе.
154+
// RU: Клиентский код может знать или не знать о Конкретном
155+
// Итераторе или классах Коллекций, в зависимости от уровня
156+
// косвенности, который вы хотите сохранить в своей программе.
155157
var collection = new WordsCollection();
156158
collection.AddItem("First");
157159
collection.AddItem("Second");
@@ -177,10 +179,9 @@ public void ClientCode()
177179

178180
class Program
179181
{
180-
public static void Main()
182+
public static void Main(string[] args)
181183
{
182-
Client client = new Client();
183-
client.ClientCode();
184+
Client.ClientCode();
184185
}
185186
}
186187
}

0 commit comments

Comments
 (0)