桥接模式(Bridge)将抽象部分与它的实现部分分离,使他们都可以独立的变化。
//Implementor.h
#ifndef _IMPLEMENTOT_H_
#define _IMPLEMENTOT_H_
#include <iostream>
using namespace std;
class Implementor
{
public:
virtual void OperationImp()=0;
};
class ConcreteImplementorA:public Implementor
{
public:
void OperationImp()
{
cout<<"ConcreteImplementA Operation..."<<endl;
}
};
class ConcreteImplementorB:public Implementor
{
public:
void OperationImp()
{
cout<<"ConcreteImplementB Operation..."<<endl;
}
};
#endif
//Abstraction.h
#ifndef _ABSTRACTION_H_
#define _ABSTRACTION_H_
class Implementor;
class Abstraction
{
protected:
Implementor* _imp;
public:
void SetImplementor(Implementor* imp)
{
_imp = imp;
}
virtual void Operation()=0;
};
class RefinedAbstraction:public Abstraction
{
public:
void Operation()
{
_imp->OperationImp();
}
};
#endif
//main.cpp
#include "Implementor.h"
#include "Abstraction.h"
int main()
{
Abstraction* ab = new RefinedAbstraction();
ab->SetImplementor(new ConcreteImplementorA());
ab->Operation();
ab->SetImplementor(new ConcreteImplementorB());
ab->Operation();
return 0;
}