桥接模式定义:
对于两个变化维度(或多个)的系统、进行各自维度的拓展、将抽象部分与她的实现部分分离,
一种对象结构模式。又称为柄体系模式或者接口模式。
本质是:类关系中的实现、关联。
实现demo:
文件BridgePattern.h
#ifndef __BRIDGE_PATTERN_H__
#define __BRIDGE_PATTERN_H__
#include <iostream>
#include <string.h>
#include <mutex>
using namespace std;
//实现类接口
class Game
{
public:
Game(){}
virtual ~Game(){};
virtual void play() = 0;
};
//具体实现类A
class GameA: public Game
{
public:
Game(){};
void play()
{
printf("Jun want play gameA\n");
}
}
//具体实现类B
class GmaeB: public Gmae
{
public:
Game(){};
void play(){
printf("Jun want play GameB\n");
}
}
//抽象类
class Phone
{
public:
Phone(){};
virtual ~Phone(){};
virtual void setupGame(Game *igame) = 0;
virtual void play() = 0;
private:
Game *game;
}
//扩充抽象类A
class PhoneA: public Phone
{
public:
PhoneA(){};
~PhoneA(){};
void setupGame(Game* igame){
this->game = igame;
}
void play(){
this->game->play();
}
private:
Game* game;
}
//扩充抽象类B
class PhoneB:public Phone
{
public:
PhoneA(){};
~PhoneA(){};
void setupGmae(Game* igame)
{
this->game = igame;
}
void play()
{
this->game->play();
}
private:
Game* game;
}
main.cpp
#include <iostream>
#include "BridgePattern.h"
int main(){
//先声明两个抽象类,在实现的时候进行具体类的分配
Game * game;
Phone * phone;
//完成jun想在phoneA上玩游戏A的事件。
//Jun 想在手机A 上玩游戏A 游戏B 同理想在手机B上玩A 和B 随着样式选择越多,需要实现的品类越
多,但是在手机B 玩游戏B 这个事件可能不会发生,属于无效代码,
//这种设计模式完全可以积木式解决这个事件,减少代码量,灵活适配
//像桥一样,最少路径实现,桥接
//开始实现jun想在手机A玩游戏A
phone = new PhoneA();
game = new GameA();
phone->setupGame(game);
phone->play();
delete game;
//开始实现jun想在手机A 玩游戏B
game = new GameB();
phone->setupGame(game);
phone->play();
delete phone;
delete game;
return 0;
}