设计模式之桥接模式
LDK Lv4

桥接模式

桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分与其实现部分分离,使它们都可以独立变化。这种模式有时也被称作柄体(Handle and Body)模式接口隔离模式。它的主要目的是将抽象层与实现层解耦,使得两者可以独立扩展而互不影响。核心是委托:将对自己的调用委托给其他对象。

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
/** 
* Implementation类 定义了所有 Implementation类 的子类的接口。它不需要匹配 Abstraction 类的接口。
* 其实两接口可以完全不同。
* 通常,Implementation类 接口只提供原始操作,而 Abstraction类 定义了更高的--基于这些原语的级别操作。
*/

class Implementation {
public:
virtual ~Implementation() {}
virtual std::string OperationImplementation() const = 0;
};

// 具体实现 (Concrete Implementations) 中包括特定于平台的代码

class ConcreteImplementationA : public Implementation {
public:
std::string OperationImplementation() const override {
return "ConcreteImplementationA: Here's the result on the platform A.\n";
}
};

class ConcreteImplementationB : public Implementation {
public:
std::string OperationImplementation() const override {
return "ConcreteImplementationB: Here's the result on the platform B.\n";
}
};

// Abstraction类 定义了“控制”部分的接口。它管理着一个指向Implementation类对象的引用,并会将所有真实工作委派给该对象。

class Abstraction {
/**
* @var Implementation
*/
protected:
Implementation *implementation_;

public:
Abstraction(Implementation *implementation) :
implementation_(implementation) {}

virtual ~Abstraction() {}

virtual std::string Operation() const {
return "Abstraction: Base operation with:\n" +
this->implementation_->OperationImplementation();
}
};

class ExtendedAbstraction : public Abstraction {
public:
ExtendedAbstraction(Implementation *implementation) :
Abstraction(implementation) {}

std::string Operation() const override {
return "ExtendedAbstraction: Extended operation with:\n" +
this->implementation_->OperationImplementation();
}
};

void ClientCode(const Abstraction &abstraction) {
// ...
std::cout << abstraction.Operation();
// ...
}

int main() {
Implementation *implementation = new ConcreteImplementationA;
Abstraction *abstraction = new Abstraction(implementation);
ClientCode(*abstraction);
std::cout << std::endl;
delete implementation;
delete abstraction;

implementation = new ConcreteImplementationB;
abstraction = new ExtendedAbstraction(implementation);
ClientCode(*abstraction);

delete implementation;
delete abstraction;

return 0;
}
由 Hexo 驱动 & 主题 Keep
本站由 提供部署服务
总字数 74.8k 访客数 访问量