案例:不同的手机品牌,运行不同的通讯录和游戏
桥接模式
桥接模式简介(BridgePattern)
桥接模式将两个独立变化的维度设计成两个独立的继承等级结构,在抽象层建立起两者的关联关系,将抽象部分与它的实现部分分离,使它们可以独立地变化
桥接模式结构
- Abstract(抽象类): 抽象类定义抽象业务方法接口,聚合了一个Implementor对象
- Implementor(实现类): 实现类定义抽象基本操作接口
- RefindeAbstraction(扩充抽象类): 实现抽象类接口,调用Implemento中的方法
- ConcreteImplementor(具体实现类): 实现不同的具体操作
桥接模式示例
https://gitee.com/NiMiKiss/design-pattern.git
#ifndef _BRIDGE_PATTERN_
#define _BRIDGE_PATTERN_
#include<iostream>
class HandsetSoft
{
public:
virtual void Run() = 0;
};
class HandsetGame :public HandsetSoft
{
public:
void Run()
{
std::cout << "运行手机游戏" << std::endl;
}
};
class HandsetAddressList :public HandsetSoft
{
public:
void Run()
{
std::cout << "运行手机通讯录" << std::endl;
}
};
class HandsetBrand
{
public:
virtual void Run() = 0;
void SetHandsetSoft(std::shared_ptr<HandsetSoft> spHandsetSoft) { m_spHandsetSoft = spHandsetSoft; }
protected:
std::shared_ptr<HandsetSoft> m_spHandsetSoft;
};
class HandsetBrandN :public HandsetBrand
{
public:
void Run()
{
m_spHandsetSoft->Run();
}
};
class HandsetBrandM :public HandsetBrand
{
public:
void Run()
{
m_spHandsetSoft->Run();
}
};
#endif // !_BRIDGE_PATTERN_
客户端调用
#include "Bridge_Pattern.h"
#include<iostream>
int main()
{
auto spHandsetGame = std::shared_ptr<HandsetGame>(new HandsetGame());
auto spHandsetBrandM = std::shared_ptr<HandsetBrandM>(new HandsetBrandM());
spHandsetBrandM->SetHandsetSoft(spHandsetGame);
spHandsetBrandM->Run();
return EXIT_SUCCESS;
}