桥接模式(Bridge Pattern)是将抽象部分与它的实现部分分离,使它们都可以独立地变化。1
模式结构
UML 结构图:
Abstraction(抽象类):用于定义抽象类的接口,并且维护一个指向 Implementor 实现类的指针。它与 Implementor 之间具有关联关系。
RefinedAbstraction(扩充抽象类):扩充由 Abstraction 定义的接口,在 RefinedAbstraction 中可以调用在 Implementor 中定义的业务方法。
Implementor(实现类接口):定义实现类的接口,这个接口不一定要与 Abstraction 的接口完全一致,事实上这两个接口可以完全不同。
ConcreteImplementor(具体实现类):实现了 Implementor 定义的接口,在不同的 ConcreteImplementor 中提供基本操作的不同实现。在程序运行时,ConcreteImplementor 对象将替换其父类对象,提供给 Abstraction 具体的业务操作方法。
案例分析
对于开关和电器来说,不管任何时候,都可以在不触及另一方的情况下进行更换。比如,可以在不更换开关的情况下换掉灯泡(或风扇),也可以在不接触灯泡(或风扇)的情况下更换掉开关,甚至可以在不接触开关的情况下将灯泡和风扇互换。
这看起来很自然,当然也应该是这样!当不同的事物联系到一起时,它们应该在一个可以变更或者替换的系统中,以便不相互影响或者使影响尽可能的小,这样才能更方便、更低成本地去管理系统。试想一下,如果要更换房间里的一个灯泡,还必须把开关也换了,你会考虑使用这样的系统吗?
代码实现
创建实现类接口
所有电器都有一些共性,可以被打开和关闭:
// implementor.h
#ifndef IMPLEMENTOR_H
#define IMPLEMENTOR_H// 电器
class IEquipment
{
public:virtual ~IEquipment() {}// 打开virtual void PowerOn() = 0;// 关闭virtual void PowerOff() = 0;
};#endif // IMPLEMENTOR_H
创建具体实现类
接下来,是真正的电器 - 电灯和风扇,它们实现了 IEquipment 接口:
// concrete_implementor.h
#ifndef CONCRETE_IMPLEMENTOR_H
#define CONCRETE_IMPLEMENTOR_H#include "implementor.h"
#include // 电灯
class Light : public IEquipment
{
public:// 开灯void PowerOn() override {std::cout << "Light is on." << std::endl;}// 关灯void PowerOff() override {std::cout << "Light is off." << std::endl;}
};// 风扇
class Fan : public IEquipment
{
public:// 打开风扇void PowerOn() override {std::cout << "Fan is on." << std::endl;}// 关闭风扇void PowerOff() override {std::cout << "Fan is off." << std::endl;}
};#endif // CONCRETE_IMPLEMENTOR_H
创建客户端
很好,是时候将开关和电器关联起来了:
// main.cpp
#include "refined_abstraction.h"
#include "concrete_implementor.h"#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete p; p=nullptr;} }
#endifint main()
{// 创建电器 - 电灯、风扇IEquipment *light = new Light();IEquipment *fan = new Fan();/*** 创建开关 - 拉链式开关、两位开关* 将拉链式开关和电灯关联起来,将两位开关和风扇关联起来**/ISwitch *pullChain = new PullChainSwitch(light);ISwitch *twoPosition = new TwoPositionSwitch(fan);// 开灯、关灯pullChain->On();pullChain->Off();// 打开风扇、关闭风扇twoPosition->On();twoPosition->Off();SAFE_DELETE(twoPosition);SAFE_DELETE(pullChain);SAFE_DELETE(fan);SAFE_DELETE(light);getchar();return 0;
}
输出如下:
Switch on the equipment with a pull chain switch.
Light is on.
Switch off the equipment with a pull chain switch.
Light is off.
Switch on the equipment with a two-position switch.
Fan is on.
Switch off the equipment with a two-position switch.
Fan is off.
声明:
本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。