(十五)桥接模式
桥接模式(Bridge),将抽象部分和它的实现部分分离,使他们都可以独立地变化。[DP]
抽象和实现分离,并不是说,让抽象类与其派生类分离,因为这没有任何意义。
实现,指的是抽象类和它的派生类用来实现自己的对象。
在发现我们需要多角度去分类实现对象,而只用继承会造成大量的类增加,不能满足开放-封闭原则,就应该考虑用桥接模式了。
#include <iostream>
using namespace std;
class Implementor
{
public:
virtual void Operation() = 0;
};
class ConcreteImplementorA :public Implementor
{
public:
void Operation()override{
cout << "Concrete Implementor Operation A" << endl;
}
};
class ConcreteImplementorB :public Implementor
{
public:
void Operation()override{
cout << "Concrete Implementor Operation B" << endl;
}
};
class Abstraction
{
public:
void SetImplementor(Implementor *impl){
this->impl = impl;
}
virtual void Operation(){
impl->Operation();
}
protected:
Implementor *impl;
};
class RedfinedAbstraction :public Abstraction
{
public:
void Operation()override{
impl->Operation();
}
};
int main()
{
Abstraction *abs = new RedfinedAbstraction();
Implementor *impla = new ConcreteImplementorA();
abs->SetImplementor(impla);
abs->Operation();
Implementor *implb = new ConcreteImplementorB();
abs->SetImplementor(implb);
abs->Operation();
delete abs;
delete impla;
delete implb;
return 0;
}