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 ;
2
14
3
15
namespace RefactoringGuru . DesignPatterns . FactoryMethod . Conceptual
4
16
{
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
+ // реализацию этого метода.
5
24
abstract class Creator
6
25
{
26
+ // EN: Note that the Creator may also provide some default
27
+ // implementation of the factory method.
28
+ //
29
+ // RU: Обратите внимание, что Создатель может также обеспечить
30
+ // реализацию фабричного метода по умолчанию.
7
31
public abstract IProduct FactoryMethod ( ) ;
8
32
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
+ // из него другой тип продукта.
9
46
public string SomeOperation ( )
10
47
{
48
+ // EN: Call the factory method to create a Product object.
49
+ //
50
+ // RU: Вызываем фабричный метод, чтобы получить объект-продукт.
11
51
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 ( ) ;
14
57
15
58
return result ;
16
59
}
17
60
}
18
61
62
+ // EN: Concrete Creators override the factory method in order to change the
63
+ // resulting product's type.
64
+ //
65
+ // RU: Конкретные Создатели переопределяют фабричный метод для того, чтобы
66
+ // изменить тип результирующего продукта.
19
67
class ConcreteCreator1 : Creator
20
68
{
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
+ // независимым от конкретных классов продуктов.
21
78
public override IProduct FactoryMethod ( )
22
79
{
23
80
return new ConcreteProduct1 ( ) ;
@@ -32,11 +89,21 @@ public override IProduct FactoryMethod()
32
89
}
33
90
}
34
91
92
+ // EN: The Product interface declares the operations that all concrete
93
+ // products must implement.
94
+ //
95
+ // RU: Интерфейс Продукта объявляет операции, которые должны выполнять все
96
+ // конкретные продукты.
35
97
interface IProduct
36
98
{
37
99
string Operation ( ) ;
38
100
}
39
101
102
+ // EN: Concrete Products provide various implementations of the Product
103
+ // interface.
104
+ //
105
+ // RU: Конкретные Продукты предоставляют различные реализации интерфейса
106
+ // Продукта.
40
107
class ConcreteProduct1 : IProduct
41
108
{
42
109
public string Operation ( )
@@ -58,19 +125,28 @@ class Client
58
125
public void Main ( )
59
126
{
60
127
Console . WriteLine ( "App: Launched with the ConcreteCreator1." ) ;
61
- ClientMethod ( new ConcreteCreator1 ( ) ) ;
128
+ ClientCode ( new ConcreteCreator1 ( ) ) ;
62
129
63
130
Console . WriteLine ( "" ) ;
64
131
65
132
Console . WriteLine ( "App: Launched with the ConcreteCreator2." ) ;
66
- ClientMethod ( new ConcreteCreator2 ( ) ) ;
133
+ ClientCode ( new ConcreteCreator2 ( ) ) ;
67
134
}
68
135
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 )
70
146
{
71
147
// ...
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 ( ) ) ;
74
150
// ...
75
151
}
76
152
}
0 commit comments