Skip to content

Commit 7489c0b

Browse files
Eder DuranEder Duran
authored andcommitted
Initial commit Factory Method
1 parent b95813d commit 7489c0b

File tree

2 files changed

+192
-0
lines changed

2 files changed

+192
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
App: Launched with the ConcreteCreator1.
2+
Client: I'm not aware of the creator's class, but it still works.
3+
Creator: The same creator's code has just worked with {Result of the ConcreteProduct1}
4+
5+
App: Launched with the ConcreteCreator2.
6+
Client: I'm not aware of the creator's class, but it still works.
7+
Creator: The same creator's code has just worked with {Result of the ConcreteProduct2}
8+

src/FactoryMethod/Conceptual/main.cc

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
#include <string>
2+
#include <iostream>
3+
4+
/**
5+
* EN: Factory Method Design Pattern
6+
*
7+
* Intent: Provides an interface for creating objects in a superclass, but
8+
* allows subclasses to alter the type of objects that will be created.
9+
*
10+
* RU: Паттерн Фабричный Метод
11+
*
12+
* Назначение: Определяет общий интерфейс для создания объектов в суперклассе,
13+
* позволяя подклассам изменять тип создаваемых объектов.
14+
*/
15+
16+
17+
/**
18+
* EN: The Product interface declares the operations that all concrete products
19+
* must implement.
20+
*
21+
* RU: Интерфейс Продукта объявляет операции, которые должны выполнять все
22+
* конкретные продукты.
23+
*/
24+
25+
class Product{
26+
public:
27+
virtual ~Product(){}
28+
virtual std::string Operation() const =0;
29+
};
30+
31+
/**
32+
* EN: Concrete Products provide various implementations of the Product
33+
* interface.
34+
*
35+
* RU: Конкретные Продукты предоставляют различные реализации интерфейса
36+
* Продукта.
37+
*/
38+
class ConcreteProduct1 : public Product{
39+
40+
public:
41+
42+
std::string Operation() const override {
43+
return "{Result of the ConcreteProduct1}";
44+
}
45+
};
46+
class ConcreteProduct2 : public Product{
47+
public:
48+
49+
std::string Operation() const override {
50+
return "{Result of the ConcreteProduct2}";
51+
}
52+
};
53+
54+
55+
/**
56+
* EN: The Creator class declares the factory method that is supposed to return
57+
* an object of a Product class. The Creator's subclasses usually provide the
58+
* implementation of this method.
59+
*
60+
* RU: Класс Создатель объявляет фабричный метод, который должен возвращать
61+
* объект класса Продукт. Подклассы Создателя обычно предоставляют реализацию
62+
* этого метода.
63+
*/
64+
65+
class Creator{
66+
/**
67+
* EN: Note that the Creator may also provide some default implementation of
68+
* the factory method.
69+
*
70+
* RU: Обратите внимание, что Создатель может также обеспечить реализацию
71+
* фабричного метода по умолчанию.
72+
*/
73+
public:
74+
virtual ~Creator(){};
75+
virtual Product* FactoryMethod() const=0 ;
76+
/**
77+
* EN: Also note that, despite its name, the Creator's primary
78+
* responsibility is not creating products. Usually, it contains some core
79+
* business logic that relies on Product objects, returned by the factory
80+
* method. Subclasses can indirectly change that business logic by
81+
* overriding the factory method and returning a different type of product
82+
* from it.
83+
*
84+
* RU: Также заметьте, что, несмотря на название, основная обязанность
85+
* Создателя не заключается в создании продуктов. Обычно он содержит
86+
* некоторую базовую бизнес-логику, которая основана на объектах Продуктов,
87+
* возвращаемых фабричным методом. Подклассы могут косвенно изменять эту
88+
* бизнес-логику, переопределяя фабричный метод и возвращая из него другой
89+
* тип продукта.
90+
*/
91+
92+
std::string SomeOperation() const {
93+
// EN: Call the factory method to create a Product object.
94+
//
95+
// RU: Вызываем фабричный метод, чтобы получить объект-продукт.
96+
Product* product= this->FactoryMethod();
97+
// EN: Now, use the product.
98+
//
99+
// RU: Далее, работаем с этим продуктом.
100+
std::string result= "Creator: The same creator's code has just worked with "+ product->Operation();
101+
delete product;
102+
return result;
103+
}
104+
};
105+
106+
107+
108+
109+
110+
111+
/**
112+
* EN: Concrete Creators override the factory method in order to change the
113+
* resulting product's type.
114+
*
115+
* RU: Конкретные Создатели переопределяют фабричный метод для того, чтобы
116+
* изменить тип результирующего продукта.
117+
*/
118+
class ConcreteCreator1: public Creator{
119+
/**
120+
* EN: Note that the signature of the method still uses the abstract product
121+
* type, even though the concrete product is actually returned from the
122+
* method. This way the Creator can stay independent of concrete product
123+
* classes.
124+
*
125+
* RU: Обратите внимание, что сигнатура метода по-прежнему использует тип
126+
* абстрактного продукта, хотя фактически из метода возвращается конкретный
127+
* продукт. Таким образом, Создатель может оставаться независимым от
128+
* конкретных классов продуктов.
129+
*/
130+
public:
131+
132+
Product* FactoryMethod() const override {
133+
return new ConcreteProduct1();
134+
}
135+
};
136+
137+
class ConcreteCreator2: public Creator
138+
{
139+
public:
140+
141+
Product* FactoryMethod() const override{
142+
return new ConcreteProduct2();
143+
}
144+
};
145+
146+
/**
147+
* EN: The client code works with an instance of a concrete creator, albeit
148+
* through its base interface. As long as the client keeps working with the
149+
* creator via the base interface, you can pass it any creator's subclass.
150+
*
151+
* RU: Клиентский код работает с экземпляром конкретного создателя, хотя и через
152+
* его базовый интерфейс. Пока клиент продолжает работать с создателем через
153+
* базовый интерфейс, вы можете передать ему любой подкласс создателя.
154+
*/
155+
void ClientCode(const Creator& creator)
156+
{
157+
// ...
158+
std::cout << "Client: I'm not aware of the creator's class, but it still works.\n"
159+
<< creator.SomeOperation()<<std::endl;
160+
// ...
161+
}
162+
163+
/**
164+
* EN: The Application picks a creator's type depending on the configuration or
165+
* environment.
166+
*
167+
* RU: Приложение выбирает тип создателя в зависимости от конфигурации или
168+
* среды.
169+
*/
170+
171+
int main(){
172+
173+
std::cout << "App: Launched with the ConcreteCreator1.\n";
174+
Creator* creator= new ConcreteCreator1();
175+
ClientCode(*creator);
176+
std::cout << std::endl;
177+
std::cout << "App: Launched with the ConcreteCreator2.\n";
178+
Creator* creator2= new ConcreteCreator2();
179+
ClientCode(*creator2);
180+
181+
delete creator;
182+
delete creator2;
183+
return 0;
184+
}

0 commit comments

Comments
 (0)