Skip to content

Commit 4cb6113

Browse files
committed
Factory method: improve conceptual example
1 parent 0b10913 commit 4cb6113

File tree

1 file changed

+84
-8
lines changed

1 file changed

+84
-8
lines changed

FactoryMethod.Conceptual/Program.cs

Lines changed: 84 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,80 @@
1-
using System;
1+
// EN: Factory Method Design Pattern
2+
//
3+
// Intent: Define an interface for creating an object, but let subclasses decide
4+
// which class to instantiate. Factory Method lets a class defer instantiation
5+
// to subclasses.
6+
//
7+
// RU: Паттерн Фабричный Метод
8+
//
9+
// Назначение: Определяет интерфейс для создания объекта, но позволяет
10+
// подклассам решать, какого класса создавать экземпляр. Фабричный Метод
11+
// позволяет классу делегировать создание экземпляра подклассам.
12+
13+
using System;
214

315
namespace RefactoringGuru.DesignPatterns.FactoryMethod.Conceptual
416
{
17+
// EN: The Creator class declares the factory method that is supposed to
18+
// return an object of a Product class. The Creator's subclasses usually
19+
// provide the implementation of this method.
20+
//
21+
// RU: Класс Создатель объявляет фабричный метод, который должен возвращать
22+
// объект класса Продукт. Подклассы Создателя обычно предоставляют
23+
// реализацию этого метода.
524
abstract class Creator
625
{
26+
// EN: Note that the Creator may also provide some default
27+
// implementation of the factory method.
28+
//
29+
// RU: Обратите внимание, что Создатель может также обеспечить
30+
// реализацию фабричного метода по умолчанию.
731
public abstract IProduct FactoryMethod();
832

33+
// EN: Also note that, despite its name, the Creator's primary
34+
// responsibility is not creating products. Usually, it contains some
35+
// core business logic that relies on Product objects, returned by the
36+
// factory method. Subclasses can indirectly change that business logic
37+
// by overriding the factory method and returning a different type of
38+
// product from it.
39+
//
40+
// RU: Также заметьте, что, несмотря на название, основная обязанность
41+
// Создателя не заключается в создании продуктов. Обычно он содержит
42+
// некоторую базовую бизнес-логику, которая основана на объектах
43+
// Продуктов, возвращаемых фабричным методом. Подклассы могут косвенно
44+
// изменять эту бизнес-логику, переопределяя фабричный метод и возвращая
45+
// из него другой тип продукта.
946
public string SomeOperation()
1047
{
48+
// EN: Call the factory method to create a Product object.
49+
//
50+
// RU: Вызываем фабричный метод, чтобы получить объект-продукт.
1151
var product = FactoryMethod();
12-
13-
var result = "Creator: The same creator's code has just worked with " + product.Operation();
52+
// EN: Now, use the product.
53+
//
54+
// RU: Далее, работаем с этим продуктом.
55+
var result = "Creator: The same creator's code has just worked with "
56+
+ product.Operation();
1457

1558
return result;
1659
}
1760
}
1861

62+
// EN: Concrete Creators override the factory method in order to change the
63+
// resulting product's type.
64+
//
65+
// RU: Конкретные Создатели переопределяют фабричный метод для того, чтобы
66+
// изменить тип результирующего продукта.
1967
class ConcreteCreator1 : Creator
2068
{
69+
// EN: Note that the signature of the method still uses the abstract
70+
// product type, even though the concrete product is actually returned
71+
// from the method. This way the Creator can stay independent of
72+
// concrete product classes.
73+
//
74+
// RU: Обратите внимание, что сигнатура метода по-прежнему использует
75+
// тип абстрактного продукта, хотя фактически из метода возвращается
76+
// конкретный продукт. Таким образом, Создатель может оставаться
77+
// независимым от конкретных классов продуктов.
2178
public override IProduct FactoryMethod()
2279
{
2380
return new ConcreteProduct1();
@@ -32,11 +89,21 @@ public override IProduct FactoryMethod()
3289
}
3390
}
3491

92+
// EN: The Product interface declares the operations that all concrete
93+
// products must implement.
94+
//
95+
// RU: Интерфейс Продукта объявляет операции, которые должны выполнять все
96+
// конкретные продукты.
3597
interface IProduct
3698
{
3799
string Operation();
38100
}
39101

102+
// EN: Concrete Products provide various implementations of the Product
103+
// interface.
104+
//
105+
// RU: Конкретные Продукты предоставляют различные реализации интерфейса
106+
// Продукта.
40107
class ConcreteProduct1 : IProduct
41108
{
42109
public string Operation()
@@ -58,19 +125,28 @@ class Client
58125
public void Main()
59126
{
60127
Console.WriteLine("App: Launched with the ConcreteCreator1.");
61-
ClientMethod(new ConcreteCreator1());
128+
ClientCode(new ConcreteCreator1());
62129

63130
Console.WriteLine("");
64131

65132
Console.WriteLine("App: Launched with the ConcreteCreator2.");
66-
ClientMethod(new ConcreteCreator2());
133+
ClientCode(new ConcreteCreator2());
67134
}
68135

69-
public void ClientMethod(Creator creator)
136+
// EN: The client code works with an instance of a concrete creator,
137+
// albeit through its base interface. As long as the client keeps
138+
// working with the creator via the base interface, you can pass it any
139+
// creator's subclass.
140+
//
141+
// RU: Клиентский код работает с экземпляром конкретного создателя, хотя
142+
// и через его базовый интерфейс. Пока клиент продолжает работать с
143+
// создателем через базовый интерфейс, вы можете передать ему любой
144+
// подкласс создателя.
145+
public void ClientCode(Creator creator)
70146
{
71147
// ...
72-
Console.WriteLine("Client: I'm not aware of the creator's class, but it still works.\n"
73-
+ creator.SomeOperation());
148+
Console.WriteLine("Client: I'm not aware of the creator's class," +
149+
"but it still works.\n" + creator.SomeOperation());
74150
// ...
75151
}
76152
}

0 commit comments

Comments
 (0)