mardi 7 juillet 2020

Question about Bridge Pattern implementation

Recently, I've made several attempts to understand a Bridge Pattern. Different websites are trying to explain this concept in different ways, but I'm beginning to understand this pattern - decouple abstraction and implementation - allows us to make different kinds of implementations, and additionally, we are able to extend our interface. But I just want to make sure with one thing - based on example below:

#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();
}

What if I wanted to make different messages for TV and Radio? Should I make a virtual methods in Device called "volumeUp()" and "VolumeDown()" which will be inherited by Radio and TV? And RemoteController would only call these virtual methods?

Aucun commentaire:

Enregistrer un commentaire