Skip to content

Commit df63285

Browse files
committed
Chain of responsibility: improve conceptual example
1 parent 67264df commit df63285

File tree

2 files changed

+66
-19
lines changed

2 files changed

+66
-19
lines changed
Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
Chain: Monkey > Squirerel > Dog
1+
Chain: Monkey > Squirrel > Dog
22

33
Client: Who wants a Nut?
4-
Squirrel: I'll eat the Nut.Client: Who wants a Banana?
5-
Monkey: I'll eat the Banana
4+
Squirrel: I'll eat the Nut.
5+
Client: Who wants a Banana?
6+
Monkey: I'll eat the Banana.
67
Client: Who wants a Cup of coffee?
78
Cup of coffee was left untouched.
89

910
Subchain: Squirrel > Dog
1011

1112
Client: Who wants a Nut?
12-
Squirrel: I'll eat the Nut.Client: Who wants a Banana?
13+
Squirrel: I'll eat the Nut.
14+
Client: Who wants a Banana?
1315
Banana was left untouched.
1416
Client: Who wants a Cup of coffee?
1517
Cup of coffee was left untouched.

ChainOfResponsibility.Conceptual/Program.cs

Lines changed: 60 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,61 @@
1-
using System;
1+
// EN: Chain of Responsibility Design Pattern
2+
//
3+
// Intent: Avoid coupling a sender of a request to its receiver by giving more
4+
// than one object a chance to handle the request. Chain the receiving objects
5+
// and then pass the request through the chain until some receiver handles it.
6+
//
7+
// RU: Паттерн Цепочка обязанностей
8+
//
9+
// Назначение: Позволяет избежать привязки отправителя запроса к его получателю,
10+
// предоставляя возможность обработать запрос нескольким объектам. Связывает в
11+
// цепочку объекты-получатели, а затем передаёт запрос по цепочке, пока некий
12+
// получатель не обработает его.
13+
14+
using System;
215
using System.Collections.Generic;
316

417
namespace RefactoringGuru.DesignPatterns.ChainOfResponsibility.Conceptual
518
{
19+
// EN: The Handler interface declares a method for building the chain of
20+
// handlers. It also declares a method for executing a request.
21+
//
22+
// RU: Интерфейс Обработчика объявляет метод построения цепочки
23+
// обработчиков. Он также объявляет метод для выполнения запроса.
624
interface Handler
725
{
8-
Handler setNext(Handler handler);
26+
Handler SetNext(Handler handler);
927

1028
object Handle(object request);
1129
}
1230

31+
// EN: The default chaining behavior can be implemented inside a base handler
32+
// class.
33+
//
34+
// RU: Поведение цепочки по умолчанию может быть реализовано внутри базового
35+
// класса обработчика.
1336
abstract class AbstractHandler : Handler
1437
{
15-
private Handler nextHandler;
38+
private Handler _nextHandler;
1639

17-
public Handler setNext(Handler handler)
40+
public Handler SetNext(Handler handler)
1841
{
19-
this.nextHandler = handler;
42+
this._nextHandler = handler;
43+
44+
// EN: Returning a handler from here will let us link handlers in a
45+
// convenient way like this:
46+
// monkey.SetNext(squirrel).SetNext(dog);
47+
//
48+
// RU: Возврат обработчика отсюда позволит связать обработчики
49+
// простым способом, вот так:
50+
// monkey.SetNext(squirrel).SetNext(dog);
2051
return handler;
2152
}
2253

2354
public virtual object Handle(object request)
2455
{
25-
if (this.nextHandler != null)
56+
if (this._nextHandler != null)
2657
{
27-
return this.nextHandler.Handle(request);
58+
return this._nextHandler.Handle(request);
2859
}
2960
else
3061
{
@@ -39,7 +70,7 @@ public override object Handle(object request)
3970
{
4071
if ((request as string) == "Banana")
4172
{
42-
return "Monkey: I'll eat the " + request.ToString() + ".\n";
73+
return $"Monkey: I'll eat the {request.ToString()}.\n";
4374
}
4475
else
4576
{
@@ -54,7 +85,7 @@ public override object Handle(object request)
5485
{
5586
if (request.ToString() == "Nut")
5687
{
57-
return "Squirrel: I'll eat the " + request.ToString() + ".\n";
88+
return $"Squirrel: I'll eat the {request.ToString()}.\n";
5889
}
5990
else
6091
{
@@ -69,7 +100,7 @@ public override object Handle(object request)
69100
{
70101
if (request.ToString() == "MeatBall")
71102
{
72-
return "Dog: I'll eat the " + request.ToString() + ".\n";
103+
return $"Dog: I'll eat the {request.ToString()}.\n";
73104
}
74105
else
75106
{
@@ -80,21 +111,27 @@ public override object Handle(object request)
80111

81112
class Client
82113
{
114+
// EN: The client code is usually suited to work with a single handler. In most
115+
// cases, it is not even aware that the handler is part of a chain.
116+
//
117+
// RU: Обычно клиентский код приспособлен для работы с единственным
118+
// обработчиком. В большинстве случаев клиенту даже неизвестно, что этот
119+
// обработчик является частью цепочки.
83120
public static void ClientCode(AbstractHandler handler)
84121
{
85122
foreach (var food in new List<string> { "Nut", "Banana", "Cup of coffee" })
86123
{
87-
Console.WriteLine("Client: Who wants a " + food + "?");
124+
Console.WriteLine($"Client: Who wants a {food}?");
88125

89126
var result = handler.Handle(food);
90127

91128
if (result != null)
92129
{
93-
Console.Write(" " + result);
130+
Console.Write($" {result}");
94131
}
95132
else
96133
{
97-
Console.WriteLine(" " + food + " was left untouched.");
134+
Console.WriteLine($" {food} was left untouched.");
98135
}
99136
}
100137
}
@@ -104,13 +141,21 @@ class Program
104141
{
105142
static void Main(string[] args)
106143
{
144+
// EN: The other part of the client code constructs the actual chain.
145+
//
146+
// RU: Другая часть клиентского кода создает саму цепочку.
107147
var monkey = new MonkeyHandler();
108148
var squirrel = new SquirrelHandler();
109149
var dog = new DogHandler();
110150

111-
monkey.setNext(squirrel).setNext(dog);
151+
monkey.SetNext(squirrel).SetNext(dog);
112152

113-
Console.WriteLine("Chain: Monkey > Squirerel > Dog\n");
153+
// EN: The client should be able to send a request to any handler, not just the
154+
// first one in the chain.
155+
//
156+
// RU: Клиент должен иметь возможность отправлять запрос любому обработчику, а
157+
// не только первому в цепочке.
158+
Console.WriteLine("Chain: Monkey > Squirrel > Dog\n");
114159
Client.ClientCode(monkey);
115160
Console.WriteLine();
116161

0 commit comments

Comments
 (0)