1.桥接模式简介
桥接模式:将抽象部分和它的实现部分分离,使它们都可以独立的变化。通俗的说,当一个系统有多角度分类,并且每一种分类都可能有变化时,就可以将这种多角度分离出来,让他们独立变化,减少他们之间的耦合。UML类图如下:
2.实例
桥接模式其实也是采用了优先使用合成/聚合复用,而不是继承这个原则。继承是一定是一种is-a的关系,当不是这种关系是,尽量不要继承。不然父类和子类是一种强耦合的关系,如果父类改变,子类都要改变。采用桥接模式完成手机安装软件的设计,UML类图如下:
c 代码实现如下:
代码语言:javascript复制#include<exception>
#include <iostream>
#include<string>
#include<list>
using namespace std;
//12.桥接模式:手机安装软件
class Soft
{
public:
virtual ~Soft(){}
virtual void run() = 0;
};
class GameSoft :public Soft
{
public:
void run() override
{
cout << "run game" << endl;
}
};
class TelSoft :public Soft
{
public:
void run()override
{
cout << "run telephone" << endl;
}
};
class Phone
{
public:
virtual ~Phone(){}
void setSoft(Soft *ipSoft)
{
m_pSoft = ipSoft;
}
virtual void run() = 0;
protected:
Soft *m_pSoft;
};
class Xiaomi :public Phone
{
public:
void run() override
{
m_pSoft->run();
}
};
class Huawei :public Phone
{
public:
void run() override
{
m_pSoft->run();
}
};
int main()
{
Soft *pSoft1 = new GameSoft;
Soft *pSoft2 = new TelSoft;
Phone *phone = new Huawei;
phone->setSoft(pSoft1);
phone->run();
phone->setSoft(pSoft2);
phone->run();
delete pSoft1;
delete pSoft2;
delete phone;
system("pause");
}
3.总结
优先has -a,其次is -a