橋模式,其作用就是讓抽象與實現相分離,讓兩者都能夠各自變化
簡單實現代碼如下:
#include<iostream>
using namespace std;
class Implementor
{
public:
virtual void Operation()=0;
};
class ConcreteImplementorA:public Implementor
{
public:
virtual void Operation()
{
cout<<"具體實現A的方法執行"<<endl;
}
};
class ConcreteImplementorB:public Implementor
{
public:
virtual void Operation()
{
cout<<"具體實現B的方法執行"<<endl;
}
};
class Abstraction
{
protected:
Implementor * implementor;
public:
virtual void SetImplementor(Implementor * implementor)
{
this->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;
}