1
- using System ;
1
+ // EN: Command Design Pattern
2
+ //
3
+ // Intent: Encapsulate a request as an object, thereby letting you parameterize
4
+ // clients with different requests (e.g. queue or log requests) and support
5
+ // undoable operations.
6
+ //
7
+ // RU: Паттерн Команда
8
+ //
9
+ // Назначение: Инкапсулирует запрос как объект, позволяя тем
10
+ // самым параметризовать клиентов с различными запросами (например, запросами
11
+ // очереди или логирования) и поддерживать отмену операций.
12
+
13
+ using System ;
2
14
3
15
namespace RefactoringGuru . DesignPatterns . Command . Conceptual
4
16
{
5
- abstract class Command
17
+ // EN: The Command interface declares a method for executing a command.
18
+ //
19
+ // RU: Интерфейс Команды объявляет метод для выполнения команд.
20
+ interface Command
6
21
{
7
- public abstract void Execute ( ) ;
22
+ void Execute ( ) ;
8
23
}
9
24
25
+ // EN: Some commands can implement simple operations on their own.
26
+ //
27
+ // RU: Некоторые команды способны выполнять простые операции самостоятельно.
10
28
class SimpleCommand : Command
11
29
{
12
- string _payLoad = string . Empty ;
30
+ private string _payload = string . Empty ;
13
31
14
- public SimpleCommand ( string payLoad )
32
+ public SimpleCommand ( string payload )
15
33
{
16
- _payLoad = payLoad ;
34
+ this . _payload = payload ;
17
35
}
18
36
19
- public override void Execute ( )
37
+ public void Execute ( )
20
38
{
21
- Console . Write ( $ "SimpleCommand: See, I can do simple things like printing ({ _payLoad } ) \n ") ;
39
+ Console . WriteLine ( $ "SimpleCommand: See, I can do simple things like printing ({ this . _payload } ) ") ;
22
40
}
23
41
}
24
42
43
+ // EN: However, some commands can delegate more complex operations to other
44
+ // objects, called "receivers."
45
+ //
46
+ // RU: Но есть и команды, которые делегируют более сложные операции другим
47
+ // объектам, называемым «получателями».
25
48
class ComplexCommand : Command
26
49
{
27
- Receiver receiver ;
28
-
29
- string a ;
30
-
31
- string b ;
32
-
33
- public ComplexCommand ( Receiver r , string a , string b )
50
+ private Receiver _receiver ;
51
+
52
+ // EN: Context data, required for launching the receiver's methods.
53
+ //
54
+ // RU: Данные о контексте, необходимые для запуска методов получателя.
55
+ private string _a ;
56
+
57
+ private string _b ;
58
+
59
+ // EN: Complex commands can accept one or several receiver objects along
60
+ // with any context data via the constructor.
61
+ //
62
+ // RU: Сложные команды могут принимать один или несколько
63
+ // объектов-получателей вместе с любыми данными о контексте через
64
+ // конструктор.
65
+ public ComplexCommand ( Receiver receiver , string a , string b )
34
66
{
35
- receiver = r ;
36
- this . a = a ;
37
- this . b = b ;
67
+ this . _receiver = receiver ;
68
+ this . _a = a ;
69
+ this . _b = b ;
38
70
}
39
71
40
- public override void Execute ( )
72
+ //
73
+ // EN: Commands can delegate to any methods of a receiver.
74
+ //
75
+ // RU: Команды могут делегировать выполнение любым методам получателя.
76
+ ///
77
+ public void Execute ( )
41
78
{
42
- Console . Write ( "ComplexCommand: Complex stuff should be done by a receiver object.\n " ) ;
43
- receiver . doSomething ( a ) ;
44
- receiver . doSomethingElse ( b ) ;
79
+ Console . WriteLine ( "ComplexCommand: Complex stuff should be done by a receiver object." ) ;
80
+ this . _receiver . DoSomething ( this . _a ) ;
81
+ this . _receiver . DoSomethingElse ( this . _b ) ;
45
82
}
46
83
}
47
84
85
+ // EN: The Receiver classes contain some important business logic. They know how
86
+ // to perform all kinds of operations, associated with carrying out a request.
87
+ // In fact, any class may serve as a Receiver.
88
+ //
89
+ // RU: Классы Получателей содержат некую важную бизнес-логику. Они умеют
90
+ // выполнять все виды операций, связанных с выполнением запроса. Фактически,
91
+ // любой класс может выступать Получателем.
48
92
class Receiver
49
93
{
50
- public void doSomething ( string a )
94
+ public void DoSomething ( string a )
51
95
{
52
- Console . Write ( "Receiver: Working on (" + a + ".) \n ") ;
96
+ Console . WriteLine ( $ "Receiver: Working on ({ a } .) ") ;
53
97
}
54
98
55
- public void doSomethingElse ( string b )
99
+ public void DoSomethingElse ( string b )
56
100
{
57
- Console . Write ( "Receiver: Also working on (" + b + ".) \n ") ;
101
+ Console . WriteLine ( $ "Receiver: Also working on ({ b } .) ") ;
58
102
}
59
103
}
60
104
105
+ // EN: The Invoker is associated with one or several commands. It sends a
106
+ // request to the command.
107
+ //
108
+ // RU: Отправитель связан с одной или несколькими командами. Он отправляет запрос
109
+ // команде.
61
110
class Invoker
62
111
{
63
- Command onStart ;
112
+ private Command _onStart ;
64
113
65
- Command onFinish ;
114
+ private Command _onFinish ;
66
115
67
- public void setOnStart ( Command c )
116
+ // EN: Initialize commands.
117
+ //
118
+ // RU: Инициализация команд
119
+ public void SetOnStart ( Command command )
68
120
{
69
- onStart = c ;
121
+ this . _onStart = command ;
70
122
}
71
123
72
- public void setOnFinish ( Command c )
124
+ public void SetOnFinish ( Command command )
73
125
{
74
- onFinish = c ;
126
+ this . _onFinish = command ;
75
127
}
76
128
77
- public void doSomethingImportant ( )
129
+ // EN: The Invoker does not depend on concrete command or receiver classes.
130
+ // The Invoker passes a request to a receiver indirectly, by executing a
131
+ // command.
132
+ //
133
+ // RU: Отправитель не зависит от классов конкретных команд и получателей.
134
+ // Отправитель передаёт запрос получателю косвенно, выполняя команду.
135
+ public void DoSomethingImportant ( )
78
136
{
79
- Console . Write ( "Invoker: Does anybody want something done before I begin?\n " ) ;
80
- if ( onStart is Command )
137
+ Console . WriteLine ( "Invoker: Does anybody want something done before I begin?" ) ;
138
+ if ( this . _onStart is Command )
81
139
{
82
- onStart . Execute ( ) ;
140
+ this . _onStart . Execute ( ) ;
83
141
}
84
- Console . Write ( "Invoker: ...doing something really important...\n " ) ;
85
- Console . Write ( "Invoker: Does anybody want something done after I finish?\n " ) ;
86
- if ( onFinish is Command )
142
+
143
+ Console . WriteLine ( "Invoker: ...doing something really important..." ) ;
144
+
145
+ Console . WriteLine ( "Invoker: Does anybody want something done after I finish?" ) ;
146
+ if ( this . _onFinish is Command )
87
147
{
88
- onFinish . Execute ( ) ;
148
+ this . _onFinish . Execute ( ) ;
89
149
}
90
150
}
91
151
}
@@ -94,12 +154,15 @@ class Program
94
154
{
95
155
static void Main ( string [ ] args )
96
156
{
157
+ // EN: The client code can parameterize an invoker with any commands.
158
+ //
159
+ // RU: Клиентский код может параметризовать отправителя любыми командами.
97
160
Invoker invoker = new Invoker ( ) ;
98
- invoker . setOnStart ( new SimpleCommand ( "Say Hi!" ) ) ;
99
- Receiver r = new Receiver ( ) ;
100
- invoker . setOnFinish ( new ComplexCommand ( r , "Send email" , "Save report" ) ) ;
161
+ invoker . SetOnStart ( new SimpleCommand ( "Say Hi!" ) ) ;
162
+ Receiver receiver = new Receiver ( ) ;
163
+ invoker . SetOnFinish ( new ComplexCommand ( receiver , "Send email" , "Save report" ) ) ;
101
164
102
- invoker . doSomethingImportant ( ) ;
165
+ invoker . DoSomethingImportant ( ) ;
103
166
}
104
167
}
105
168
}
0 commit comments