桥接模式即将抽象部分与它的实现部分分离开来,使他们都可以独立变化。
桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。
github源码路径:https://github.com/dangwei-90/Design-Mode
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
// 参考大话设计模式 - 桥接模式
#include <iostream>
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif
using namespace std;
// 方法接口
class Implementor {
public:
virtual void Operation() = 0;
};
class ImplementorA : public Implementor {
public:
void Operation (){
cout << "Operation A" << endl;
}
};
class ImplementorB : public Implementor {
public:
void Operation() {
cout << "Operation B" << endl;
}
};
class Abstruction {
public:
Abstruction() {};
Abstruction(Implementor* implementor) {
implementor_ = implementor;
}
void SetImplementor(Implementor* implementor) {
implementor_ = implementor;
}
void Operation() {
implementor_->Operation();
}
private:
Implementor* implementor_ = nullptr;
};
int main()
{
Implementor* implementor = new ImplementorA();
// also , can use SetImplementor();
Abstruction* abstruction = new Abstruction(implementor);
abstruction->Operation();
SAFE_DELETE(implementor);
SAFE_DELETE(abstruction);
implementor = new ImplementorB();
abstruction = new Abstruction(implementor);
abstruction->Operation();
SAFE_DELETE(implementor);
SAFE_DELETE(abstruction);
return 0;
}