桥模式
使用场景:其作用就是让抽象与实现相分离,让两者都能够各自变化。
例子:小时候家里用的是白炽灯,开关是拉线开关,随着发展,节能灯取代白炽灯,按钮开关取代了拉线开关。开关和灯泡的关系可以看成是继承关系,因为开关可以看作是灯泡的一部分,灯泡完全拥有开关,如果真是使用继承设计,那么将无法应对开关和灯泡的变迁了,看看桥模式是怎么做的。
#include <iostream>
using namespace std;
//实现化角色
//电灯
class Light
{
public:
virtual void poweroOn() = 0;
virtual void powerOff() = 0;
};
//具体实现化角色
//白炽灯
class FilamentLight :public Light
{
public:
virtual void poweroOn()
{
cout << "白炽灯打开!" << endl;
}
virtual void powerOff()
{
cout << "白炽灯关闭!" << endl;
}
};
//节能灯
class EfficientLight :public Light
{
public:
virtual void poweroOn()
{
cout << "节能灯打开!" << endl;
}
virtual void powerOff()
{
cout << "节能灯关闭!" << endl;
}
};
//抽象角色定义
//开关
class Switch
{
public:
Switch(Light *light) :m_pLight(light){}
virtual void on() = 0;
virtual void off() = 0;
void setLight(Light *light){ m_pLight = light; }
protected:
Light *m_pLight;
};
//修正抽象化角色
//拉线开关
class PullChainSwitch :public Switch
{
public:
PullChainSwitch(Light *light) :Switch(light){}
virtual void on()
{
cout << "拉线开关打开:";
m_pLight->poweroOn();
}
virtual void off()
{
cout << "拉线开关关闭:";
m_pLight->powerOff();
}
};
//按钮开关
class ButtonSwitch :public Switch
{
public:
ButtonSwitch(Light *light) :Switch(light){}
virtual void on()
{
cout << "按钮开关打开:";
m_pLight->poweroOn();
}
virtual void off()
{
cout << "按钮开关关闭:";
m_pLight->powerOff();
}
};
//使用方法
int main()
{
//创建具体实现化角色
Light *filamentLight = new FilamentLight;//白炽灯
Light *efficientLight = new EfficientLight;//节能灯
//创建具体抽象化角色
Switch * pullChainSwitch = new PullChainSwitch(filamentLight);//白炽灯一般配拉线开关
pullChainSwitch->on();
//生活好了换了节能灯
pullChainSwitch->setLight(efficientLight);
pullChainSwitch->on();
//生活好了又换了按钮开关了
Switch * buttonSwitch = new ButtonSwitch(efficientLight);
buttonSwitch->on();
return 0;
}
输出结果:
拉线开关打开:白炽灯打开! 拉线开关打开:节能灯打开! 按钮开关打开:节能灯打开! 请按任意键继续. . .
桥梁模式是针对继承的不足提出了,一般当继承大于等于二层时,才考虑使用桥梁模式。此时才能显示出抽象变化的方便。
参考:https://blog.csdn.net/a369189453/article/details/81176196
浙公网安备 33010602011771号