参考链接:http://www.cnblogs.com/jiese/p/3164940.html
作用:将抽象部份与它的实现部份分离,使它们都可以独立地变化。
应用场景:如果只有一维在变化,那么我们用继承就可以圆满的解决问题。但是设计中有超过一维的变化我们就可以用桥模式。
《大话设计模式》中就Bridge模式的解释:
手机品牌和软件是两个概念,不同的软件可以在不同的手机上,不同的手机可以有相同的软件,两者都具有很大的变动性。如果我们单独以手机品牌或手机软件为基类来进行继承扩展的话,无疑会使类的数目剧增并且耦合性很高,(如果更改品牌或增加软件都会增加很多的变动)两种方式的结构如下:
用桥接模式解决此问题,将两者抽象出来两个基类分别是PhoneBrand和PhoneSoft,那么在品牌类中聚合一个软件对象的基类将解决软件和手机扩展混乱的问题,这样两者的扩展就相对灵活,剪短了两者的必要联系,结构图如下:
桥接模式,UML类图:
代码:
#ifndef _BRIDGE_H_
#define _BRIDGE_H_
#include <iostream>
using namespace std;
class Implementor //实现部分
{
public:
Implementor(){};
~Implementor(){};
virtual void OperationImp(){ cout << "Implementor OperationImp" << endl; }
private:
};
class ConcreteImplementorA :public Implementor
{
public:
ConcreteImplementorA(){};
~ConcreteImplementorA(){};
virtual void OperationImp(){ cout << "ConcreteImplementorA OperationImp" << endl; }
private:
};
class ConcreteImplementorB :public Implementor
{
public:
ConcreteImplementorB(){};
~ConcreteImplementorB(){};
virtual void OperationImp(){ cout << "ConcreteImplementorB OperationImp" << endl; }
private:
};
class Abstraction//抽象部分
{
public:
Abstraction(Implementor* InputImp){ this->imp = InputImp; };
~Abstraction(){};
virtual void Operation()
{
cout << "Abstraction Operation" << endl;
imp->OperationImp();
}
private:
Implementor* imp;
};
class RedefinedAbstractionA :public Abstraction
{
public:
RedefinedAbstractionA(Implementor *InputImp) :Abstraction(InputImp){}
~RedefinedAbstractionA(){};
virtual void OtherOperation()
{
cout << "RedefinedAbstractionA OtherOperation" << endl;
Operation();
}
private:
};
class RedefinedAbstractionB :public Abstraction
{
public:
RedefinedAbstractionB(Implementor *InputImp) :Abstraction(InputImp){};
~RedefinedAbstractionB(){};
virtual void Operation(){ cout << "RedefinedAbstractionB Operation" << endl; }
private:
};
#endif
client代码:
//桥接模式
ConcreteImplementorA* concreteImplementorA = new ConcreteImplementorA();
RedefinedAbstractionA* redefinedAbstractionA = new RedefinedAbstractionA(concreteImplementorA);
redefinedAbstractionA->OtherOperation();
if (concreteImplementorA)
{
delete concreteImplementorA;
concreteImplementorA = nullptr;
}
if (redefinedAbstractionA)
{
delete redefinedAbstractionA;
redefinedAbstractionA = nullptr;
}
输出:
RedefinedAbstractionA OtherOperation
Abstraction Operation
ConcreteImplementorA OperationImp
请按任意键继续. . .