桥接模式:
将抽象部分与它的实现部分分离,使它们都可以独立的变化。实现系统可能有多角度分类,每一种分类都有可能变化,每一种分类都有可能变化,桥接模式通过合成聚合原则代替继承把这种多角度分离出来让它们独立变化,减少系统的耦合度。
类图:
关键代码:
// RefinedAbstraction.h
#include "Abstraction.h"
class RefinedAbstraction : public Abstraction
{
public:
RefinedAbstraction();
RefinedAbstraction(Implementor* imp);
virtual ~RefinedAbstraction();
virtual void operation();
};
// RefinedAbstraction.cpp
#include "RefinedAbstraction.h"
#include <iostream>
using namespace std;
RefinedAbstraction::RefinedAbstraction(){
}
RefinedAbstraction::RefinedAbstraction(Implementor* imp)
:Abstraction(imp)
{
}
RefinedAbstraction::~RefinedAbstraction(){
}
void RefinedAbstraction::operation(){
cout << "do something else ,and then " << endl;
m_pImp->operationImp();
}
// ConcreteImplementorA.h
#include "Implementor.h"
class ConcreteImplementorA : public Implementor
{
public:
ConcreteImplementorA();
virtual ~ConcreteImplementorA();
virtual void operationImp();
};
// ConcreteImplementorA.cpp
#include "ConcreteImplementorA.h"
#include <iostream>
using namespace std;
ConcreteImplementorA::ConcreteImplementorA(){
}
ConcreteImplementorA::~ConcreteImplementorA(){
}
void ConcreteImplementorA::operationImp(){
cout << "imp in ConcreteImplementorA style." << endl;
}
// 客户端
#include <iostream>
#include "ConcreteImplementorA.h"
#include "ConcreteImplementorB.h"
#include "RefinedAbstraction.h"
#include "Abstraction.h"
using namespace std;
int main(int argc, char *argv[])
{
Implementor * pImp = new ConcreteImplementorA();
Abstraction * pa = new RefinedAbstraction(pImp);
pa->operation();
Abstraction * pb = new RefinedAbstraction(new ConcreteImplementorB());
pb->operation();
delete pa;
delete pb;
return 0;
}