桥梁模式(BridgePattern)也叫做桥接模式,定义为将抽象和实现解耦,使得两者可以独立地变化。
桥梁模式的重点是在“解耦”上。
桥梁模式通用类图
Abstraction
— 定义抽象类的接口。
— 维护一个指向Implementor类型对象的指针。
RefinedAbstraction
— 扩充由Abstraction定义的接口。
Implementor
— 定义实现类的接口,该接口不一定要与Abstraction的接口完全一致;事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些基本操作的较高层次的操作。
ConcreteImplementor
— 实现Implementor接口并定义它的具体实现。
桥梁模式的优点
抽象和实现分离
这也是桥梁模式的主要特点,它完全是为了解决继承的缺点而提出的设计模式,该模式下,实现可以不受抽象的约束,不再绑定在一个固定的抽象层次上。
优秀的扩充能力
可以独立地对Abstraction和Implementor层次结构进行扩充。
实现细节对客户透明
举例:
来自《Head FirstDesign Pattern》,
C++实现
#include <iostream>
using namespace std;
class TV{ //Implementor
public:
virtual void on()=0;
virtual void off()=0;
virtual void tuneChannel(int ch)=0;
virtual ~TV(){}
};
class RCA:public TV{ //ConcreteImplementor
public:
void on(){cout<<"RCA powered on"<<endl;}
void off(){cout<<"RCA powered off"<<endl;}
void tuneChannel(int ch){
cout<<"RCA Channel is changed, current channel is "<<ch<<endl;
}
};
class Sony:public TV{ //ConcreteImplementor
public:
void on(){cout<<"Sony powered on"<<endl;}
void off(){cout<<"Sony powered off"<<endl;}
void tuneChannel(int ch){
cout<<"Sony Channel is changed, current channel is "<<ch<<endl;
}
};
class RemoteControl{
protected:
TV *tv;
public:
RemoteControl(TV *_tv):tv(_tv){};
virtual void on(){tv->on();};
virtual void off(){tv->off();};
virtual void setChannel(int ch){tv->tuneChannel(ch);}
virtual ~RemoteControl(){
}
};
class ConcreteRemote:public RemoteControl{
private:
int currentState;
public:
ConcreteRemote(TV *_tv):RemoteControl(_tv){};
void setStation(int cs){
currentState=cs;
setChannel(cs);
}
void nextChannel(){setChannel(++currentState);}
void previousChannel(){setChannel(--currentState);}
};
int main()
{
RCA *rca = new RCA;
ConcreteRemote cr(rca);
cr.on();
cr.setStation(5);
cr.nextChannel();
cr.previousChannel();
cr.off();
delete rca;
Sony *sony = new Sony;
ConcreteRemote crs(sony);
crs.on();
crs.setStation(10);
crs.nextChannel();
crs.previousChannel();
crs.off();
delete sony;
return 0;
}
运行结果: