将 抽象部分与它的 实现部分解耦,使得两者能够独立变化。
模式优点
- 分离抽象接口及其实现部分
- 可以取代多层继承方案,极大地减少了子类的个数
- 提高了系统的可扩展性,在两个变化维度中任意扩展一个维度,不需要修改原有系统,符合开闭原则
模式缺点
- 会增加系统的理解与设计难度
- 正确识别出系统中的两个独立变化的维度并不是一件容易的事情
适用环境
- 需要在抽象化和具体化之间增加更多的灵活性,避免在两个层次之间建立静态的继承关系
- 抽象部分和实现部分可以以继承的方式独立扩展而互不影响
- 一个类存在两个或多个独立变化的维度,且这两个或多个维度都需要独立地进行扩展
- 不希望使用继承或因为多层继承导致系统类的个数急剧增加的系统
桥接模式代码
/*
* @ Description: C++ Design Patterns___Bridge
* @ version: v1.0
* @ Author: WeissxJ
*/
#include<iostream>
class Implementor
{
public:
virtual ~Implementor() {
}
virtual void action() = 0;
// ...
};
class ConcreteImplementorA : public Implementor
{
public:
~ConcreteImplementorA() {
}
void action()
{
std::cout << "Concrete Implementor A" << std::endl;
}
// ...
};
class ConcreteImplementorB : public Implementor
{
public:
~ConcreteImplementorB() {
}
void action()
{
std::cout << "Concrete Implementor B" << std::endl;
}
// ...
};
class Abstraction
{
public:
virtual ~Abstraction() {
}
virtual void operation() = 0;
// ...
};
class RefinedAbstraction : public Abstraction
{
public:
~RefinedAbstraction() {
}
RefinedAbstraction(Implementor *impl) : implementor(impl) {
}
void operation()
{
implementor->action();
}
// ...
private:
Implementor *implementor;
};
int main()
{
Implementor *ia = new ConcreteImplementorA;
Implementor *ib = new ConcreteImplementorB;
Abstraction *abstract1 = new RefinedAbstraction(ia);
abstract1->operation();
Abstraction *abstract2 = new RefinedAbstraction(ib);
abstract2->operation();
delete abstract1;
delete abstract2;
delete ia;
delete ib;
return 0;
}