桥接模式的UML结构图:
桥接模式主要包含如下几个角色:
// Abstraction.h
#pragma once
class AbstractionImp;
class Abstraction
{
public:
virtual ~Abstraction();
virtual void Operation() = 0;
protected:
Abstraction();
private:
};
class RefinedAbstraction :public Abstraction
{
public:
RefinedAbstraction(AbstractionImp*
imp);
~RefinedAbstraction();
void Operation();
protected:
private:
AbstractionImp* _imp;
};
//Abstraction.cpp
#include "Abstraction.h"
#include "AbstractionImp.h"
#include
using namespace std;
Abstraction::Abstraction()
{
cout << "Abstraction..." << endl;
}
Abstraction::~Abstraction()
{
cout << "~Abstraction..." << endl;
}
RefinedAbstraction::RefinedAbstraction(AbstractionImp* imp)
{
cout << "RefinedAbstraction imp..." << endl;
_imp = imp;
}
RefinedAbstraction::~RefinedAbstraction()
{
cout << "~RefinedAbstraction..." << endl;
}
void RefinedAbstraction::Operation()
{
cout << "RefinedAbstraction Operation..." << endl;
_imp->Operation();
}
//AbstractionImp.h
#pragma once
class AbstractionImp
{
public:
virtual ~AbstractionImp();
virtual void Operation() = 0;
protected:
AbstractionImp();
private:
};
class ConcreteAbstractionImpA :public
AbstractionImp
{
public:
ConcreteAbstractionImpA();
~ConcreteAbstractionImpA();
virtual void Operation();
protected:
private:
};
class ConcreteAbstractionImpB :public
AbstractionImp
{
public:
ConcreteAbstractionImpB();
~ConcreteAbstractionImpB();
virtual void Operation();
protected:
private:
};
//AbstractionImp.cpp
#include "AbstractionImp.h"
#include
using namespace std;
AbstractionImp::AbstractionImp()
{
cout << "AbstractionImp..." << endl;
}
AbstractionImp::~AbstractionImp()
{
cout << "~AbstractionImp..." << endl;
}
void AbstractionImp::Operation()
{
cout << "AbstractionImp....Operation..." << endl;
}
ConcreteAbstractionImpA::ConcreteAbstractionImpA()
{
cout << "ConcreteAbstractionImpA" << endl;
}
ConcreteAbstractionImpA::~ConcreteAbstractionImpA()
{
cout << "~ConcreteAbstractionImpA" << endl;
}
void ConcreteAbstractionImpA::Operation()
{
cout << "ConcreteAbstractionImpA....Operation...." << endl;
}
ConcreteAbstractionImpB::ConcreteAbstractionImpB()
{
cout << "ConcreteAbstractionImpB" << endl;
}
ConcreteAbstractionImpB::~ConcreteAbstractionImpB()
{
cout << "~ConcreteAbstractionImpB" << endl;
}
void ConcreteAbstractionImpB::Operation()
{
cout << "ConcreteAbstractionImpB....Operation...." << endl;
}
// main.cpp : 此文件包含 “main” 函数。程序执行将在此处开始并结束。
//
#include “Abstraction.h”
#include “AbstractionImp.h”
#include
using namespace std;
int main()
{
AbstractionImp* imp = new ConcreteAbstractionImpA();
Abstraction* abs = new RefinedAbstraction(imp);
abs->Operation();
return 0;
}
执行结果如下:
AbstractionImp...
ConcreteAbstractionImpA
Abstraction...
RefinedAbstraction imp...
RefinedAbstraction Operation...
ConcreteAbstractionImpA....Operation....