最近,我做了几次尝试来了解桥接模式。不同的网站试图以不同的方式解释这个概念,但是我开始理解这种模式-将抽象与实现分离-允许我们进行不同类型的实现,此外,我们还可以扩展我们的界面。但我只想确保一件事-基于以下示例:

#include <iostream>

class Device
{
protected:
    int volume_m{ 0 };
public:
    int getVolume()
    {
        return volume_m;
    }
    void setVolume(int value)
    {
        volume_m = value;
    }
};

class RemoteController
{
private:
    std::shared_ptr<Device> device_m;
public:
    RemoteController(std::shared_ptr<Device> device) : device_m(device) {}
    void volumeUp()
    {
        device_m->setVolume(device_m->getVolume()+10);
        std::cout << "Volume turned up. Current volume: " << device_m->getVolume() << '\n';
    }
    void volumeDown()
    {
        this->device_m->setVolume(this->device_m->getVolume() - 10);
        std::cout << "Volume turned down. Current volume: " << device_m->getVolume() << '\n';
    }

};

class TV : public Device
{

};

class Radio : public Device
{

};


int main()
{
    std::shared_ptr<Device> tv = std::make_shared<TV>();
    std::shared_ptr<RemoteController> controller = std::make_shared<RemoteController>(tv);
    controller->volumeUp();
    controller->volumeUp();
    controller->volumeUp();
}
如果我想为TVRadio发送不同的消息怎么办?我是否应该在Device中创建虚拟方法,即volumeUp()volumeDown(),它们将由RadioTV继承?而RemoteController只会调用这些虚拟方法吗?

最佳答案

是的,我相信在VolumeUpVolumeDown对象中实现Radio TV方法会更正确。因为它们对于这些对象可能会有所不同(这两者都不是步骤10)。
而且我认为最好不要在没有太多需要的情况下通过getter和setter公开您的实现。有关此here的更多信息

关于c++ - 有关桥接模式实现的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62783248/

10-15 00:15
查看更多