Skip to content

Commit 7004f58

Browse files
Eder DuranEder Duran
authored andcommitted
Bridge Pattern
1 parent a5ac74a commit 7004f58

File tree

2 files changed

+178
-0
lines changed

2 files changed

+178
-0
lines changed

src/Bridge/Conceptual/Output.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Abstraction: Base operation with:
2+
ConcreteImplementationA: Here's the result on the platform A.
3+
4+
ExtendedAbstraction: Extended operation with:
5+
ConcreteImplementationB: Here's the result on the platform B.
6+
7+

src/Bridge/Conceptual/main.cc

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
#include <iostream>
2+
#include <string>
3+
4+
/**
5+
* EN: Bridge Design Pattern
6+
*
7+
* Intent: Lets you split a large class or a set of closely related classes into
8+
* two separate hierarchies—abstraction and implementation—which can be
9+
* developed independently of each other.
10+
*
11+
* A
12+
* / \ A N
13+
* Aa Ab ===> / \ / \
14+
* / \ / \ Aa(N) Ab(N) 1 2
15+
* Aa1 Aa2 Ab1 Ab2
16+
*
17+
* RU: Паттерн Мост
18+
*
19+
* Назначение: Разделяет один или несколько классов на две отдельные иерархии —
20+
* абстракцию и реализацию, позволяя изменять их независимо друг от друга.
21+
*
22+
* A
23+
* / \ A N
24+
* Aa Ab ===> / \ / \
25+
* / \ / \ Aa(N) Ab(N) 1 2
26+
* Aa1 Aa2 Ab1 Ab2
27+
*/
28+
29+
30+
/**
31+
* EN: The Implementation defines the interface for all implementation classes.
32+
* It doesn't have to match the Abstraction's interface. In fact, the two
33+
* interfaces can be entirely different. Typically the Implementation interface
34+
* provides only primitive operations, while the Abstraction defines higher-
35+
* level operations based on those primitives.
36+
*
37+
* RU: Реализация устанавливает интерфейс для всех классов реализации. Он не
38+
* должен соответствовать интерфейсу Абстракции. На практике оба интерфейса
39+
* могут быть совершенно разными. Как правило, интерфейс Реализации
40+
* предоставляет только примитивные операции, в то время как Абстракция
41+
* определяет операции более высокого уровня, основанные на этих примитивах.
42+
*/
43+
44+
class Implementation
45+
{
46+
public:
47+
virtual ~Implementation(){}
48+
virtual std::string OperationImplementation() const =0 ;
49+
};
50+
51+
52+
/**
53+
* EN: Each Concrete Implementation corresponds to a specific platform and
54+
* implements the Implementation interface using that platform's API.
55+
*
56+
* RU: Каждая Конкретная Реализация соответствует определённой платформе и
57+
* реализует интерфейс Реализации с использованием API этой платформы.
58+
*/
59+
class ConcreteImplementationA: public Implementation
60+
{
61+
public:
62+
std::string OperationImplementation()const override
63+
{
64+
return "ConcreteImplementationA: Here's the result on the platform A.\n";
65+
}
66+
};
67+
class ConcreteImplementationB: public Implementation
68+
{
69+
public:
70+
std::string OperationImplementation()const override
71+
{
72+
return "ConcreteImplementationB: Here's the result on the platform B.\n";
73+
}
74+
};
75+
76+
/**
77+
* EN: The Abstraction defines the interface for the "control" part of the two
78+
* class hierarchies. It maintains a reference to an object of the
79+
* Implementation hierarchy and delegates all of the real work to this object.
80+
*
81+
* RU: Абстракция устанавливает интерфейс для «управляющей» части двух иерархий
82+
* классов. Она содержит ссылку на объект из иерархии Реализации и делегирует
83+
* ему всю настоящую работу.
84+
*/
85+
86+
class Abstraction{
87+
/**
88+
* @var Implementation
89+
*/
90+
protected:
91+
Implementation* implementation_;
92+
93+
public:
94+
95+
Abstraction(Implementation* implementation):implementation_(implementation){
96+
}
97+
98+
virtual ~Abstraction(){
99+
100+
}
101+
102+
virtual std::string Operation() const{
103+
return "Abstraction: Base operation with:\n" +
104+
this->implementation_->OperationImplementation();
105+
}
106+
};
107+
/**
108+
* EN: You can extend the Abstraction without changing the Implementation
109+
* classes.
110+
*
111+
* RU: Можно расширить Абстракцию без изменения классов Реализации.
112+
*/
113+
class ExtendedAbstraction : public Abstraction
114+
{
115+
public:
116+
117+
ExtendedAbstraction(Implementation* implementation): Abstraction(implementation){
118+
119+
}
120+
std::string Operation() const override
121+
{
122+
return "ExtendedAbstraction: Extended operation with:\n" +
123+
this->implementation_->OperationImplementation();
124+
}
125+
};
126+
127+
128+
/**
129+
* EN: Except for the initialization phase, where an Abstraction object gets
130+
* linked with a specific Implementation object, the client code should only
131+
* depend on the Abstraction class. This way the client code can support any
132+
* abstraction-implementation combination.
133+
*
134+
* RU: За исключением этапа инициализации, когда объект Абстракции связывается с
135+
* определённым объектом Реализации, клиентский код должен зависеть только от
136+
* класса Абстракции. Таким образом, клиентский код может поддерживать любую
137+
* комбинацию абстракции и реализации.
138+
*/
139+
void ClientCode(const Abstraction& abstraction)
140+
{
141+
// ...
142+
std::cout << abstraction.Operation();
143+
// ...
144+
}
145+
/**
146+
* EN: The client code should be able to work with any pre-configured
147+
* abstraction-implementation combination.
148+
*
149+
* RU: Клиентский код должен работать с любой предварительно сконфигурированной
150+
* комбинацией абстракции и реализации.
151+
*/
152+
153+
int main(){
154+
155+
Implementation* implementation = new ConcreteImplementationA;
156+
Abstraction* abstraction = new Abstraction(implementation);
157+
ClientCode(*abstraction);
158+
std::cout << std::endl;
159+
delete implementation;
160+
delete abstraction;
161+
162+
implementation = new ConcreteImplementationB;
163+
abstraction = new ExtendedAbstraction(implementation);
164+
ClientCode(*abstraction);
165+
166+
delete implementation;
167+
delete abstraction;
168+
169+
return 0;
170+
}
171+

0 commit comments

Comments
 (0)