先上uml图:
uml解析:桥接模式讲的就是一个解耦的问题,将抽象与实现分离开来,对接口编程,使得RefinedAbstraction对实现依赖,而不是实现依赖于RefinedAbstraction,符合依赖倒置原则。
下面给出可执行代码:
Bridge.h
#pragma once
#include <iostream>
using namespace std;
class AbtractionImplement;
class Abtraction
{
public:
Abtraction(void);
virtual ~Abtraction(void);
virtual void operation() =0;
};
class RefinedAbstraction:public Abtraction
{
public:
RefinedAbstraction(AbtractionImplement &Imp);
void operation();
private:
AbtractionImplement & m_Imp;
};
class AbtractionImplement
{
public:
virtual void operation()=0;
};
class AbtractionImplementA:public AbtractionImplement
{
public:
void operation();
};
class AbtractionImplementB:public AbtractionImplement
{
public:
void operation();
};
Bridge.cpp
#include "Abtraction.h"
Abtraction::Abtraction(void)
{
}
Abtraction::~Abtraction(void)
{
}
RefinedAbstraction::RefinedAbstraction(AbtractionImplement &Imp):m_Imp(Imp)
{
}
void RefinedAbstraction::operation()
{
m_Imp.operation();
}
void AbtractionImplementA::operation()
{
cout<<"AbtractionImplementA"<<endl;
}
void AbtractionImplementB::operation()
{
cout<<"AbtractionImplementB"<<endl;
}
main.cpp
#include "Abtraction.h"
int main(int argc,char **argv)
{
AbtractionImplementA impA;
Abtraction *f1 = new RefinedAbstraction(impA);
f1->operation();
delete f1;
AbtractionImplementB impB;
f1 = new RefinedAbstraction(impB);
f1->operation();
return 0;
}
执行之后的结果: