1
- using System ;
1
+ // EN: Strategy Design Pattern
2
+ //
3
+ // Intent: Define a family of algorithms, encapsulate each one, and make them
4
+ // interchangeable. Strategy lets the algorithm vary independently from clients
5
+ // that use it.
6
+ //
7
+ // RU: Паттерн Стратегия
8
+ //
9
+ // Назначение: Определяет семейство алгоритмов, инкапсулирует каждый из них и
10
+ // делает взаимозаменяемыми. Стратегия позволяет изменять алгоритм независимо от
11
+ // клиентов, которые его используют.
12
+
13
+ using System ;
2
14
using System . Collections . Generic ;
3
15
4
16
namespace RefactoringGuru . DesignPatterns . Strategy . Conceptual
5
17
{
18
+ // EN: The Context defines the interface of interest to clients.
19
+ //
20
+ // RU: Контекст определяет интерфейс, представляющий интерес для клиентов.
6
21
class Context
7
22
{
23
+ // EN: The Context maintains a reference to one of the Strategy objects.
24
+ // The Context does not know the concrete class of a strategy. It should
25
+ // work with all strategies via the Strategy interface.
26
+ //
27
+ // RU: Контекст хранит ссылку на один из объектов Стратегии. Контекст не
28
+ // знает конкретного класса стратегии. Он должен работать со всеми
29
+ // стратегиями через интерфейс Стратегии.
8
30
private Strategy _strategy ;
9
31
10
32
public Context ( )
11
33
{ }
12
34
35
+ // EN: Usually, the Context accepts a strategy through the constructor,
36
+ // but also provides a setter to change it at runtime.
37
+ //
38
+ // RU: Обычно Контекст принимает стратегию через конструктор, а также
39
+ // предоставляет сеттер для её изменения во время выполнения.
13
40
public Context ( Strategy strategy )
14
41
{
15
42
this . _strategy = strategy ;
16
43
}
17
44
18
- public void setStrategy ( Strategy strategy )
45
+ // EN: Usually, the Context allows replacing a Strategy object at
46
+ // runtime.
47
+ //
48
+ // RU: Обычно Контекст позволяет заменить объект Стратегии во время
49
+ // выполнения.
50
+ public void SetStrategy ( Strategy strategy )
19
51
{
20
52
this . _strategy = strategy ;
21
53
}
22
54
23
- public void doSomeBusinessLogic ( )
55
+ //
56
+ // EN: The Context delegates some work to the Strategy object instead of
57
+ // implementing multiple versions of the algorithm on its own.
58
+ //
59
+ // RU: Вместо того, чтобы самостоятельно реализовывать множественные версии
60
+ // алгоритма, Контекст делегирует некоторую работу объекту Стратегии.
61
+ ///
62
+ public void DoSomeBusinessLogic ( )
24
63
{
25
- Console . Write ( "Context: Sorting data using the strategy (not sure how it'll do it)\n " ) ;
26
- var result = this . _strategy . doAlgorithm ( new List < string > { "a" , "b" , "c" , "d" , "e" } ) ;
64
+ Console . WriteLine ( "Context: Sorting data using the strategy (not sure how it'll do it)" ) ;
65
+ var result = this . _strategy . DoAlgorithm ( new List < string > { "a" , "b" , "c" , "d" , "e" } ) ;
27
66
28
- string result_str = string . Empty ;
67
+ string resultStr = string . Empty ;
29
68
foreach ( var element in result as List < string > )
30
69
{
31
- result_str += element + "," ;
70
+ resultStr += element + "," ;
32
71
}
33
72
34
- Console . Write ( result_str ) ;
73
+ Console . WriteLine ( resultStr ) ;
35
74
}
36
75
}
37
76
77
+ // EN: The Strategy interface declares operations common to all supported
78
+ // versions of some algorithm.
79
+ //
80
+ // The Context uses this interface to call the algorithm defined by Concrete
81
+ // Strategies.
82
+ //
83
+ // RU: Интерфейс Стратегии объявляет операции, общие для всех поддерживаемых
84
+ // версий некоторого алгоритма.
85
+ //
86
+ // Контекст использует этот интерфейс для вызова алгоритма, определённого
87
+ // Конкретными Стратегиями.
38
88
interface Strategy
39
89
{
40
- object doAlgorithm ( object data ) ;
90
+ object DoAlgorithm ( object data ) ;
41
91
}
42
92
93
+ // EN: Concrete Strategies implement the algorithm while following the base
94
+ // Strategy interface. The interface makes them interchangeable in the Context.
95
+ //
96
+ // RU: Конкретные Стратегии реализуют алгоритм, следуя базовому интерфейсу
97
+ // Стратегии. Этот интерфейс делает их взаимозаменяемыми в Контексте.
43
98
class ConcreteStrategyA : Strategy
44
99
{
45
- public object doAlgorithm ( object data )
100
+ public object DoAlgorithm ( object data )
46
101
{
47
102
var list = data as List < string > ;
48
103
list . Sort ( ) ;
@@ -53,7 +108,7 @@ public object doAlgorithm(object data)
53
108
54
109
class ConcreteStrategyB : Strategy
55
110
{
56
- public object doAlgorithm ( object data )
111
+ public object DoAlgorithm ( object data )
57
112
{
58
113
var list = data as List < string > ;
59
114
list . Sort ( ) ;
@@ -67,17 +122,24 @@ class Client
67
122
{
68
123
public static void ClientCode ( )
69
124
{
125
+ // EN: The client code picks a concrete strategy and passes it to
126
+ // the context. The client should be aware of the differences
127
+ // between strategies in order to make the right choice.
128
+ //
129
+ // RU: Клиентский код выбирает конкретную стратегию и передаёт её в
130
+ // контекст. Клиент должен знать о различиях между стратегиями,
131
+ // чтобы сделать правильный выбор.
70
132
var context = new Context ( ) ;
71
133
72
- Console . Write ( "Client: Strategy is set to normal sorting.\n " ) ;
73
- context . setStrategy ( new ConcreteStrategyA ( ) ) ;
74
- context . doSomeBusinessLogic ( ) ;
75
- Console . Write ( " \n " ) ;
76
- Console . Write ( "Client: Strategy is set to reverse sorting. \n " ) ;
77
- context . setStrategy ( new ConcreteStrategyB ( ) ) ;
78
- context . doSomeBusinessLogic ( ) ;
79
-
80
- Console . Write ( " \n " ) ;
134
+ Console . WriteLine ( "Client: Strategy is set to normal sorting." ) ;
135
+ context . SetStrategy ( new ConcreteStrategyA ( ) ) ;
136
+ context . DoSomeBusinessLogic ( ) ;
137
+
138
+ Console . WriteLine ( ) ;
139
+
140
+ Console . WriteLine ( "Client: Strategy is set to reverse sorting." ) ;
141
+ context . SetStrategy ( new ConcreteStrategyB ( ) ) ;
142
+ context . DoSomeBusinessLogic ( ) ;
81
143
}
82
144
}
83
145
0 commit comments