Skip to content

Commit 5732903

Browse files
committed
Command: improve conceptual example
1 parent df63285 commit 5732903

File tree

1 file changed

+107
-44
lines changed

1 file changed

+107
-44
lines changed

Command.Conceptual/Program.cs

Lines changed: 107 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,151 @@
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;
214

315
namespace RefactoringGuru.DesignPatterns.Command.Conceptual
416
{
5-
abstract class Command
17+
// EN: The Command interface declares a method for executing a command.
18+
//
19+
// RU: Интерфейс Команды объявляет метод для выполнения команд.
20+
interface Command
621
{
7-
public abstract void Execute();
22+
void Execute();
823
}
924

25+
// EN: Some commands can implement simple operations on their own.
26+
//
27+
// RU: Некоторые команды способны выполнять простые операции самостоятельно.
1028
class SimpleCommand : Command
1129
{
12-
string _payLoad = string.Empty;
30+
private string _payload = string.Empty;
1331

14-
public SimpleCommand(string payLoad)
32+
public SimpleCommand(string payload)
1533
{
16-
_payLoad = payLoad;
34+
this._payload = payload;
1735
}
1836

19-
public override void Execute()
37+
public void Execute()
2038
{
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})");
2240
}
2341
}
2442

43+
// EN: However, some commands can delegate more complex operations to other
44+
// objects, called "receivers."
45+
//
46+
// RU: Но есть и команды, которые делегируют более сложные операции другим
47+
// объектам, называемым «получателями».
2548
class ComplexCommand : Command
2649
{
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)
3466
{
35-
receiver = r;
36-
this.a = a;
37-
this.b = b;
67+
this._receiver = receiver;
68+
this._a = a;
69+
this._b = b;
3870
}
3971

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()
4178
{
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);
4582
}
4683
}
4784

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+
// любой класс может выступать Получателем.
4892
class Receiver
4993
{
50-
public void doSomething(string a)
94+
public void DoSomething(string a)
5195
{
52-
Console.Write("Receiver: Working on (" + a + ".)\n");
96+
Console.WriteLine($"Receiver: Working on ({a}.)");
5397
}
5498

55-
public void doSomethingElse(string b)
99+
public void DoSomethingElse(string b)
56100
{
57-
Console.Write("Receiver: Also working on (" + b + ".)\n");
101+
Console.WriteLine($"Receiver: Also working on ({b}.)");
58102
}
59103
}
60104

105+
// EN: The Invoker is associated with one or several commands. It sends a
106+
// request to the command.
107+
//
108+
// RU: Отправитель связан с одной или несколькими командами. Он отправляет запрос
109+
// команде.
61110
class Invoker
62111
{
63-
Command onStart;
112+
private Command _onStart;
64113

65-
Command onFinish;
114+
private Command _onFinish;
66115

67-
public void setOnStart(Command c)
116+
// EN: Initialize commands.
117+
//
118+
// RU: Инициализация команд
119+
public void SetOnStart(Command command)
68120
{
69-
onStart = c;
121+
this._onStart = command;
70122
}
71123

72-
public void setOnFinish(Command c)
124+
public void SetOnFinish(Command command)
73125
{
74-
onFinish = c;
126+
this._onFinish = command;
75127
}
76128

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()
78136
{
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)
81139
{
82-
onStart.Execute();
140+
this._onStart.Execute();
83141
}
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)
87147
{
88-
onFinish.Execute();
148+
this._onFinish.Execute();
89149
}
90150
}
91151
}
@@ -94,12 +154,15 @@ class Program
94154
{
95155
static void Main(string[] args)
96156
{
157+
// EN: The client code can parameterize an invoker with any commands.
158+
//
159+
// RU: Клиентский код может параметризовать отправителя любыми командами.
97160
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"));
101164

102-
invoker.doSomethingImportant();
165+
invoker.DoSomethingImportant();
103166
}
104167
}
105168
}

0 commit comments

Comments
 (0)