-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBridgePattern.cpp
More file actions
102 lines (75 loc) · 2.48 KB
/
Copy pathBridgePattern.cpp
File metadata and controls
102 lines (75 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**************************************************************************
* 桥接模式
*
意图:将抽象部分与实现部分分离,使它们都可以独立的变化。
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。
如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
关键代码:抽象类依赖实现类。
应用实例: 1、猪八戒从天蓬元帅转世投胎到猪,转世投胎的机制将尘世划分为两个等级,即:灵魂和肉体,前者相当于抽象化,后者相当于实现化。生灵通过功能的委派,调用肉体对象的功能,使得生灵可以动态地选择。
2、墙上的开关,可以看到的开关是抽象的,不用管里面具体怎么实现的。
优点: 1、抽象和实现的分离。 2、优秀的扩展能力。 3、实现细节对客户透明。
缺点:桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
使用场景: 1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。 3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
注意事项:对于两个独立变化的维度,使用桥接模式再适合不过了。
**************************************************************************/
#include <iostream>
class DrawAPI
{
public:
virtual void drawCircle(int radius, int x, int y) {};
private:
};
class RedCircle : public DrawAPI
{
public:
void drawCircle(int radius, int x, int y)
{
std::cout << "Drawing Circle[ color: red, radius: "
<< radius << ", x: " << x << ", " << y << "]"<<std::endl;
}
};
class GreenCircle : public DrawAPI
{
public:
void drawCircle(int radius, int x, int y)
{
std::cout << "Drawing Circle[ color: green, radius: "
<< radius << ", x: " << x << ", " << y <<"]"<<std::endl;
}
};
class Shape
{
public:
virtual void draw() = 0;
protected:
DrawAPI* drawAPI;
Shape(DrawAPI* drawAPI) {
this->drawAPI = drawAPI;
}
private:
};
class Circle : public Shape {
private:
int x, y, radius;
public:
Circle(int x, int y, int radius, DrawAPI* drawAPI) :
x(x), y(y), radius(radius), Shape(drawAPI)
{
}
void draw() {
drawAPI->drawCircle(radius, x, y);
}
};
void main()
{
//抽象和实现分离
//shape 不知道DrawAPI的实现和变化,通过抽象来连接具体的实现(多态)
DrawAPI* a = new RedCircle();
DrawAPI* b = new GreenCircle();
Shape* redCircle = new Circle(100, 100, 10, a);
Shape* greenCircle = new Circle(100, 100, 10,b);
redCircle->draw();
greenCircle->draw();
}