桥接模式的重点在“解耦”,桥接模式主要是通过聚合和继承行为来让不同的类承担不同的责任。
桥接模式的主要特点是把抽象与行为实现分离出来,从而可以保持各部分的独立性以及对他们的功能扩展。
如上图,比如给车安装发动机,有不同种型号的车和不同种型号的发动机(看成两个不同的集合),中间通过聚合来实现两个集合的连接,
可以实现解耦,不同的车可以安装不同种型号的发动机,不会有耦合。
实现引擎发动机的抽象类engine。
#ifndef ENGINE_H
#define ENGINE_H
#include <string>
#include <iostream>
using namespace std;
class engine
{
public:
engine(std::string str);
virtual ~engine();
virtual void installEngine() = 0;
protected:
std::string m_name;
};
#endif // ENGINE_H
实现车的抽象类car,成员中有个引擎engine 类的引用,就是所谓的桥接。
#ifndef CAR_H
#define CAR_H
#include "engine.h"
#include <string>
using namespace std;
class car
{
public:
car( engine* pEngine);
virtual void installEngine() = 0;
virtual~car();
protected:
engine* m_pEngine;
};
#endif // CAR_H
具体car 和engine 实现类
#ifndef BENZENGINE_H
#define BENZENGINE_H
#include "engine.h"
class benzEngine: public engine
{
public:
benzEngine(string strname);
~benzEngine();
void installEngine();
};
#endif // BENZENGINE_H
#ifndef BMWENGIN_H
#define BMWENGIN_H
#include "engine.h"
class bmwEgine:public engine
{
public:
bmwEgine(string strname);
~bmwEgine();
void installEngine();
};
#endif // BMWENGIN_H
#ifndef BENZCAR_H
#define BENZCAR_H
#include "car.h"
#include <iostream>
class benzCar:public car
{
public:
benzCar(engine* pEngine);
void installEngine();
};
#endif // BENZCAR_H
#ifndef BMWCAR_H
#define BMWCAR_H
#include "car.h"
class BmwCar:public car
{
public:
BmwCar(engine* pEngine );
void installEngine();
};
#endif // BMWCAR_H
benzCar::benzCar(engine* pEngine):car(pEngine){}
void benzCar::installEngine(){
m_pEngine->installEngine();
}
BmwCar::BmwCar(engine* pEngine): car(pEngine){}
void BmwCar::installEngine(){
m_pEngine->installEngine();
}
benzEngine::benzEngine(string strname): engine(strname){}
void benzEngine::installEngine(){
cout<< "使用引擎: "<< m_name <<" 安装 benz car! "<<endl;
}
benzEngine::~benzEngine(){}
bmwEgine::bmwEgine(string name):engine(name){}
void bmwEgine::installEngine(){
cout<< "使用引擎: "<< m_name <<" 安装 bmw car! "<<endl;
}
bmwEgine::~bmwEgine(){}
场景类
//练习桥接模式:给(车)安装(发动机)
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
engine * pEngine = new benzEngine("benz engine num_007");
car * pcar = new benzCar(pEngine);
pcar->installEngine();
delete pEngine;
delete pcar;
pEngine = new bmwEgine("bmw engine num_911");
pcar = new BmwCar(pEngine);
pcar->installEngine();
delete pEngine;
delete pcar;
return a.exec();
}