设计模式之桥接模式C++简单实现

2014-11-23 20:10:36 · 作者: · 浏览: 17

桥模式,其作用就是让抽象与实现相分离,让两者都能够各自变化

简单实现代码如下:

#include
using namespace std;
class Implementor
{
public:
	virtual void Operation()=0;
};
class ConcreteImplementorA:public Implementor
{
public:
	virtual void Operation()
	{
		cout<<"具体实现A的方法执行"<implementor=implementor;
	}
	virtual void Operation()=0;
	virtual ~Abstraction(){}
};
class RefinedAbstraction:public Abstraction
{
public:
	virtual void Operation()
	{
		implementor->Operation();
	}
	virtual ~RefinedAbstraction()
	{
		if(implementor)
			delete implementor;
	}
};
int main()
{
	Abstraction * ab=new RefinedAbstraction();
	ab->SetImplementor(new ConcreteImplementorA());
	ab->Operation();
	delete ab;
	ab=new RefinedAbstraction();
	ab->SetImplementor(new ConcreteImplementorB());
	ab->Operation();
	delete ab;
	return 0;
}