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个类
相关推荐
会编程的土豆15 分钟前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
所以遗憾是什么呢?2 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
白藏y2 小时前
【C++】muduo接口补充
开发语言·c++·muduo
xiaoye-duck3 小时前
《算法题讲解指南:递归,搜索与回溯算法--综合练习》--14.找出所有子集的异或总和再求和,15.全排列Ⅱ,16.电话号码的字母组合,17.括号生成
c++·算法·深度优先·回溯
OOJO3 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
Tanecious.3 小时前
蓝桥杯备赛:Day5-P1706 全排列问题
c++·蓝桥杯
胖咕噜的稞达鸭4 小时前
C++技术岗面试经验总结
开发语言·网络·c++·网络协议·tcp/ip·面试
Wild_Pointer.4 小时前
高效工具实战指南:从零开始编写CMakeLists
c++
kpl_205 小时前
智能指针(C++)
c++·c++11·智能指针