简介
桥接模式(Bridge):将抽象部分与它的实现部分分离,使他们都能够独立地变化。
作用
解决在有多种可能会变化的情况下,用继承会造成类越来越复杂问题,扩展起来不灵活。
应用场景
设计中有超过一维的变化我们就可以用桥模式。如果只有一维在变化,那么我们用继承就可以圆满的解决问题。
代码如下:
#include <iostream>
#include <string>
#include <memory>
///
//软件基类
class software
{
public:
software(void){}
virtual ~software(void){}
public:
virtual void opt(void) = 0;
};
//手机基类
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;
};
///
//苹果手机
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();
}
};
//华为手机
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();
}
};
///
//软件 :王者荣耀
class wangzhe : public software
{
public:
wangzhe(void){}
virtual ~wangzhe(void){}
public:
virtual void opt(void)
{
std::cout << "opt : 王者荣耀 !" << std::endl;
}
};
//软件 : 淘宝
class taobao : public software
{
public:
taobao(void){}
virtual ~taobao(void){}
public:
virtual void opt(void)
{
std::cout << "opt : 淘宝 !" << 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;
}
运行结果: