Skip to content

Commit 59aa01c

Browse files
committed
Strategy: improve conceptual example
1 parent 64cb7b9 commit 59aa01c

File tree

1 file changed

+82
-20
lines changed

1 file changed

+82
-20
lines changed

Strategy.Conceptual/Program.cs

Lines changed: 82 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,103 @@
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;
214
using System.Collections.Generic;
315

416
namespace RefactoringGuru.DesignPatterns.Strategy.Conceptual
517
{
18+
// EN: The Context defines the interface of interest to clients.
19+
//
20+
// RU: Контекст определяет интерфейс, представляющий интерес для клиентов.
621
class Context
722
{
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+
// стратегиями через интерфейс Стратегии.
830
private Strategy _strategy;
931

1032
public Context()
1133
{ }
1234

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+
// предоставляет сеттер для её изменения во время выполнения.
1340
public Context(Strategy strategy)
1441
{
1542
this._strategy = strategy;
1643
}
1744

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)
1951
{
2052
this._strategy = strategy;
2153
}
2254

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()
2463
{
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" });
2766

28-
string result_str = string.Empty;
67+
string resultStr = string.Empty;
2968
foreach (var element in result as List<string>)
3069
{
31-
result_str += element + ",";
70+
resultStr += element + ",";
3271
}
3372

34-
Console.Write(result_str);
73+
Console.WriteLine(resultStr);
3574
}
3675
}
3776

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+
// Конкретными Стратегиями.
3888
interface Strategy
3989
{
40-
object doAlgorithm(object data);
90+
object DoAlgorithm(object data);
4191
}
4292

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+
// Стратегии. Этот интерфейс делает их взаимозаменяемыми в Контексте.
4398
class ConcreteStrategyA : Strategy
4499
{
45-
public object doAlgorithm(object data)
100+
public object DoAlgorithm(object data)
46101
{
47102
var list = data as List<string>;
48103
list.Sort();
@@ -53,7 +108,7 @@ public object doAlgorithm(object data)
53108

54109
class ConcreteStrategyB : Strategy
55110
{
56-
public object doAlgorithm(object data)
111+
public object DoAlgorithm(object data)
57112
{
58113
var list = data as List<string>;
59114
list.Sort();
@@ -67,17 +122,24 @@ class Client
67122
{
68123
public static void ClientCode()
69124
{
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+
// чтобы сделать правильный выбор.
70132
var context = new Context();
71133

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();
81143
}
82144
}
83145

0 commit comments

Comments
 (0)