C++ 设计模式-桥接模式

C++桥接模式的经典示例,包含测试代码:

cpp 复制代码
#include <iostream>
#include <string>

// 实现化接口
class Device {
public:
    virtual ~Device() = default;
    virtual bool isEnabled() const = 0;
    virtual void enable() = 0;
    virtual void disable() = 0;
    virtual void setVolume(int volume) = 0;
    virtual void setChannel(int channel) = 0;
    virtual int getVolume() const = 0;
    virtual int getChannel() const = 0;
    virtual std::string getName() const = 0;
};

// 具体实现化类:电视机
class TV : public Device {
private:
    bool enabled_ = false;
    int volume_ = 0;
    int channel_ = 1;

public:
    std::string getName() const override { return "TV"; }
    bool isEnabled() const override { return enabled_; }
    void enable() override { enabled_ = true; }
    void disable() override { enabled_ = false; }
    void setVolume(int volume) override { volume_ = volume; }
    void setChannel(int channel) override { channel_ = channel; }
    int getVolume() const override { return volume_; }
    int getChannel() const override { return channel_; }
};

// 具体实现化类:收音机
class Radio : public Device {
private:
    bool enabled_ = false;
    int volume_ = 0;
    int channel_ = 100;

public:
    std::string getName() const override { return "Radio"; }
    bool isEnabled() const override { return enabled_; }
    void enable() override { enabled_ = true; }
    void disable() override { enabled_ = false; }
    void setVolume(int volume) override { volume_ = volume; }
    void setChannel(int channel) override { channel_ = channel; }
    int getVolume() const override { return volume_; }
    int getChannel() const override { return channel_; }
};

// 抽象化类:遥控器
class RemoteControl {
protected:
    Device* device_;
public:
    RemoteControl(Device* device) : device_(device) {}
    virtual ~RemoteControl() = default;

    void togglePower() {
        if (device_->isEnabled()) {
            device_->disable();
        } else {
            device_->enable();
        }
    }

    void volumeUp() {
        device_->setVolume(device_->getVolume() + 10);
    }

    void volumeDown() {
        device_->setVolume(device_->getVolume() - 10);
    }

    void channelUp() {
        device_->setChannel(device_->getChannel() + 1);
    }

    void channelDown() {
        device_->setChannel(device_->getChannel() - 1);
    }

    virtual void printStatus() const {
        std::cout << device_->getName() << " status: "
                  << (device_->isEnabled() ? "On" : "Off")
                  << ", Volume: " << device_->getVolume()
                  << ", Channel: " << device_->getChannel() << "\n";
    }
};

// 扩展抽象化类:高级遥控器
class AdvancedRemoteControl : public RemoteControl {
public:
    AdvancedRemoteControl(Device* device) : RemoteControl(device) {}

    void mute() {
        device_->setVolume(0);
    }

    void printStatus() const override {
        RemoteControl::printStatus();
        std::cout << "[Advanced features available]\n";
    }
};

// 测试代码
int main() {
    TV tv;
    Radio radio;

    // 基本遥控器控制电视
    RemoteControl basicRemote(&tv);
    std::cout << "=== Testing Basic Remote with TV ===\n";
    basicRemote.printStatus();
    
    basicRemote.togglePower();
    basicRemote.volumeUp();
    basicRemote.volumeUp();
    basicRemote.channelUp();
    basicRemote.printStatus();

    // 高级遥控器控制收音机
    AdvancedRemoteControl advancedRemote(&radio);
    std::cout << "\n=== Testing Advanced Remote with Radio ===\n";
    advancedRemote.printStatus();
    
    advancedRemote.togglePower();
    advancedRemote.mute();
    advancedRemote.channelUp();
    advancedRemote.channelUp();
    advancedRemote.printStatus();

    // 展示独立变化特性:使用高级遥控器控制电视
    AdvancedRemoteControl advancedTVRemote(&tv);
    std::cout << "\n=== Testing Advanced Remote with TV ===\n";
    advancedTVRemote.togglePower();
    advancedTVRemote.mute();
    advancedTVRemote.channelUp();
    advancedTVRemote.printStatus();

    return 0;
}

代码说明:

  1. 实现化接口(Device):定义设备的基本操作,包括电源管理、音量和频道控制。
  2. 具体实现化类(TV/Radio):实现Device接口,分别代表不同的设备类型。
  3. 抽象化类(RemoteControl)
    • 包含一个Device指针,通过组合方式桥接实现层
    • 提供基本遥控功能(开关、音量/频道调节)
  4. 扩展抽象化类(AdvancedRemoteControl)
    • 继承基础遥控器功能
    • 添加高级功能(静音)
    • 演示抽象层的扩展不影响实现层

测试输出:

复制代码
=== Testing Basic Remote with TV ===
TV status: Off, Volume: 0, Channel: 1
TV status: On, Volume: 20, Channel: 2

=== Testing Advanced Remote with Radio ===
Radio status: Off, Volume: 0, Channel: 100
[Advanced features available]
Radio status: On, Volume: 0, Channel: 102
[Advanced features available]

=== Testing Advanced Remote with TV ===
TV status: On, Volume: 0, Channel: 3
[Advanced features available]

模式优势:

  1. 解耦抽象和实现:遥控器与设备独立变化,新增设备类型或遥控功能无需修改对方代码
  2. 可扩展性强:可以单独添加新的遥控器类型(如游戏手柄)或新设备类型(如投影仪)
  3. 避免类爆炸:M个遥控器×N个设备的组合只需M+N个类,而非M×N个类
相关推荐
zh_xuan20 分钟前
c++ 单例模式
开发语言·c++·单例模式
利刃大大3 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面3 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked933 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
虚拟之4 小时前
36、stringstream
c++
我很好我还能学4 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++
南岩亦凛汀5 小时前
在Linux下使用wxWidgets进行跨平台GUI开发
c++·跨平台·gui·开源框架·工程实战教程
曦月逸霜5 小时前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
蔡蓝6 小时前
设计模式-建造者模式
服务器·设计模式·建造者模式
galaxy_strive6 小时前
绘制饼图详细过程
开发语言·c++·qt