Bridge(DesignPattern)

Bridge

目的

将抽象部分与它的实现部分分离,使得它们都可以独立地完成变化

动机

当一个抽象对象有多个实现时,通常的实现方式是通过继承来构造。但在某些情况下,子类的实现可能会不够灵活,出现大量重复的代码,也很难对其进行独立的修改。例如有一个公路1,公路2类,和一个角色A、B类,我们需要实现的实例是A在公路1,A在公路2等四个组合方式。但其出现了大量冗余,因为它们的动作是重复的。这时我们可以使用桥接的方式来构造它们。

使用范围

  • 不希望在抽象和它的实现部分有有一个固定的绑定关系,甚至乎,我希望能够在程序运行时动态地切换实现部分
  • 希望对不同的抽象接口和实现部分进行组合
  • 对一个抽象的修改不会影响客户

效果

  • 由于接口和实现是独立的,因此可以分离接口及其实现部分
  • 提高可扩充性,由于抽象和实现是独立的,我可以在两个层次做扩充,但不会影响客户
  • 隐藏实现细节,客户无需知道内部具体的实现细节

代码示例

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
// Bridge.cpp : ¶¨Òå¿ØÖÆ̨ӦÓóÌÐòµÄÈë¿Úµã¡£
//

#include <iostream>

class Implementor {
public:
virtual void OperationImp() = 0;
virtual ~Implementor() {}
protected:
Implementor() {}
};

class ConcreteImplementor : public Implementor {
public:
virtual void OperationImp() {
std::cout << "ConcreteImplementor::OperationImp()" << std::endl;
}
};

class Abstraction {
public:
virtual void operation() = 0;
virtual ~Abstraction() {}
protected:
Abstraction() {}
public:
Implementor* imp;
};

class RefinedAbstratcion : public Abstraction{
public:
RefinedAbstratcion(Implementor* imp) {
_imp = imp;
}
virtual void operation() {
_imp->OperationImp();
std::cout << "RefinedAbstratcion::operation()" << std::endl;
}
private:
Implementor* _imp;
};



int main()
{
Implementor* imp = new ConcreteImplementor();
Abstraction* abs = new RefinedAbstratcion(imp);

abs->operation();
delete imp;
delete abs;
return 0;
}