桥接模式(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;
}
本文介绍了一种设计模式——桥接模式,它通过将抽象与其实现分离来达到两者能够独立变化的目的。文中提供了具体的C++代码示例,包括定义了抽象类及其实现类,并演示了如何在运行时切换不同的实现。
1421

被折叠的 条评论
为什么被折叠?



