桥接模式 (Bridge Pattern)
意图:将抽象部分与实现部分分离,使它们可以独立变化。
基础组件
- Abstraction (抽象部分):定义高层控制逻辑
- RefinedAbstraction (扩充抽象):扩展抽象部分接口
- Implementor (实现者接口):定义底层实现接口
- ConcreteImplementor (具体实现者):实现Implementor接口
继承/实现关系
Implementor <|-- ConcreteImplementor
Abstraction --> Implementor (组合关系)
Abstraction <|-- RefinedAbstraction
应用场景
- 需要避免抽象和实现之间的永久绑定
- 抽象和实现都需要通过子类化独立扩展
- 实现部分的改变不应影响客户端代码
C++ 实现(远程控制场景)
#include <iostream>
#include <memory>
#include <string>
/*
* 桥接模式
* 意图:将抽象部分与实现部分分离,使它们可以独立变化。
* 基础组件:
* - Abstraction (抽象部分):定义高层控制逻辑
* - RefinedAbstraction (扩充抽象):扩展抽象部分接口
* - Implementor (实现者接口):定义底层实现接口
* - ConcreteImplementor (具体实现者):实现Implementor接口
* 继承/实现关系:
* ConcreteImplementor 实现 Implementor 接口
* RefinedAbstraction 继承 Abstraction
* Implementor 接口由 Abstraction 持有(组合关系)
*/
// 实现者接口:设备
class Device {
public:
virtual void turnOn() = 0;
virtual void turnOff() = 0;
virtual void setChannel(int channel) = 0;
virtual ~Device() = default;
};
// 具体实现者:电视
class TV : public Device {
public:
void turnOn() override { std::cout << "TV turned on\n"; }
void turnOff() override { std::cout << "TV turned off\n"; }
void setChannel(int channel) override {
std::cout << "TV set to channel " << channel << "\n";
}
};
// 具体实现者:收音机
class Radio : public Device {
public:
void turnOn() override { std::cout << "Radio turned on\n"; }
void turnOff() override { std::cout << "Radio turned off\n"; }
void setChannel(int channel) override {
std::cout << "Radio tuned to station " << channel << "\n";
}
};
// 抽象部分:遥控器
class RemoteControl {
public:
RemoteControl(std::unique_ptr<Device> device) : device_(std::move(device)) {}
virtual void powerOn() { device_->turnOn(); }
virtual void powerOff() { device_->turnOff(); }
virtual void setChannel(int channel) { device_->setChannel(channel); }
virtual ~RemoteControl() = default;
protected:
// 桥接模式的核心,这个变量即为桥
std::unique_ptr<Device> device_;
};
// 扩充抽象:高级遥控器
class AdvancedRemote : public RemoteControl {
public:
// 继承基类所有构造函数
using RemoteControl::RemoteControl;
void mute() {
device_->setChannel(0);
std::cout << "Device muted\n";
}
};
void BridgePattern()
{
std::cout << std::string(13, '-') << " Bridge Pattern " << std::string(13, '-') << "\n";
std::unique_ptr<RemoteControl> tvRemote = std::make_unique<RemoteControl>(std::make_unique<TV>());
tvRemote->powerOn();
tvRemote->setChannel(5);
std::unique_ptr<AdvancedRemote> radioRemote = std::make_unique<AdvancedRemote>(std::make_unique<Radio>());
radioRemote->powerOn();
radioRemote->setChannel(101);
radioRemote->mute();
}
组件对应关系
Device→ 实现者接口TV/Radio→ 具体实现者RemoteControl→ 抽象部分AdvancedRemote→ 扩充抽象
831

被折叠的 条评论
为什么被折叠?



