<aside> 💡

桥接模式(Bridge):将抽象部分与它的实现部分分离,使它们都可以独立地变化

</aside>

结构图

image.png

应用场景

题目

https://kamacoder.com/problempage.php?pid=1092

#include <iostream>
#include <string>

// 1.创建实现类接口(Implementor)
// 一个遥控器的功能根据电视的品牌有不同的实现方式
class TVBrand{
public:
    virtual void turnOn() = 0;
    virtual void turnOff() = 0;
    virtual void switchChannel() = 0;
};

// 2.创建具体实现类(ConcreteImplementor)
class SonyTV: public TVBrand{
    void turnOn() override {
        std::cout << "Sony TV is ON" << std::endl;
    }

    void turnOff() override {
        std::cout << "Sony TV is OFF" << std::endl;
    }

    void switchChannel() override {
        std::cout << "Switching Sony TV channel" << std::endl;
    }
};

class TCLTV: public TVBrand{
    void turnOn() override {
        std::cout << "TCL TV is ON" << std::endl;
    }

    void turnOff() override {
        std::cout << "TCL TV is OFF" << std::endl;
    }

    void switchChannel() override {
        std::cout << "Switching TCL TV channel" << std::endl;
    }
};

// 3.创建抽象接口(Abstract),接口中包含一个对实现类接口的引用
class RemoteController{
protected:
    TVBrand* tv;

public:
    RemoteController(TVBrand* tv): tv(tv){};

    virtual void run() = 0;
};

// 4.实现抽象接口(RefinedAbstract)
// 抽象接口将具体实现委托给实现类
class OnButton: public RemoteController{
public:
    OnButton(TVBrand* tv): RemoteController(tv){}

    void run() override {
        tv->turnOn();
    }
};

class OffButton: public RemoteController{
public:
    OffButton(TVBrand* tv): RemoteController(tv){}

    void run() override {
        tv->turnOff();
    }
};

class SwitchButton: public RemoteController{
public:
    SwitchButton(TVBrand* tv): RemoteController(tv){}

    void run() override {
        tv->switchChannel();
    }
};

int main(){
    int n;
    std::cin >> n;

    for(int i = 0; i < n; ++i){
        int tvType;
        int option;
        std::cin >> tvType >> option;

        TVBrand* tv = nullptr;
        if(tvType == 0){
            tv = new SonyTV();
        }else if(tvType == 1){
            tv = new TCLTV();
        }else{
            std::cout << "Invalid TV" << std::endl;
            continue;
        }

        RemoteController* controller = nullptr;
        switch(option){
        case 2:
            controller = new OnButton(tv);
            break;
        case 3:
            controller = new OffButton(tv);
            break;
        case 4:
            controller = new SwitchButton(tv);
            break;
        default:
            std::cout << "Invalid Option" << std::endl;
        }

        // 将抽象接口与实现组合后,使用统一接口调用
        controller->run();

        delete tv;
        delete controller;
    }

    return 0;
}