brief introduction
Bridge: separate the abstract from its implementation so that they can all change independently.
Effect
To solve the problem of more and more complex classes and inflexible extension when there are many possible changes.
Application scenario
If there are more than one dimension changes in the design, we can use the bridge mode. If only one dimension is changing, then we can use inheritance to solve the problem successfully.
The code is as follows:
#include <iostream> #include <string> #include <memory> /////////////////////////////////////// //Software base class class software { public: software(void){} virtual ~software(void){} public: virtual void opt(void) = 0; }; //Mobile phone base class class mobilephone { public: mobilephone(void){} virtual ~mobilephone(void){} public: virtual void opt() = 0; }; class mobilephone_sw { public: mobilephone_sw(std::shared_ptr<software> sw) : m_software(sw) { } virtual ~mobilephone_sw(void){} public: virtual void opt() = 0; std::shared_ptr<software> m_software; }; /////////////////////////////////////// //IPhone class iphone : public mobilephone_sw { public: iphone(std::shared_ptr<software> sw) : mobilephone_sw(sw){} virtual ~iphone(void){} public: void opt(void) { std::cout << "opt : this is iphone" << std::endl; m_software->opt(); } }; //HUAWEI mobile phone class huawei : public mobilephone_sw { public: huawei(std::shared_ptr<software> sw): mobilephone_sw(sw){} virtual ~huawei(void){} public: void opt(void) { std::cout << "opt : this is huawei" << std::endl; m_software->opt(); } }; /////////////////////////////////////// //Software: glory of the king class wangzhe : public software { public: wangzhe(void){} virtual ~wangzhe(void){} public: virtual void opt(void) { std::cout << "opt : Glory of Kings!" << std::endl; } }; //Software: Taobao class taobao : public software { public: taobao(void){} virtual ~taobao(void){} public: virtual void opt(void) { std::cout << "opt : TaoBao!" << std::endl; } }; /////////////////////////////////////// int main() { std::cout << "start-up .." << std::endl; std::shared_ptr<wangzhe> p_wz = std::make_shared<wangzhe>(); std::shared_ptr<taobao> p_tb = std::make_shared<taobao>(); std::shared_ptr<iphone> p_ip = std::make_shared<iphone>(p_wz); std::shared_ptr<huawei> p_hw = std::make_shared<huawei>(p_tb); p_ip->opt(); p_hw->opt(); std::cout << "done .." << std::endl; return 0; }
Operation result: