桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。
这里需要解释一下,什么叫抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己地对象。
将抽象部分与实现部分分离,使它们都可以独立的变化。
在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
Implementor类
class Implementor
{
public:
virtual void Operation() = 0;
};
ConcreteImplementorA和ConcreteImplementorB等派生类
class ConcreteImplementorA : public Implementor
{
public:
void Operation() override
{
cout<<"具体实现A的方法执行"<<endl;
}
};
class ConcreteImplementorB : public Implementor
{
public:
void Operation() override
{
cout<<"具体实现B的方法执行"<<endl;
}
};
Abstraction类
class Abstraction
{
protected:
Implementor * implementor;
public:
void SetImplementor(Implementor * implementor)
{
this->implementor = implementor;
}
virtual void Operation()
{
implementor->Operation();
}
};
RefinedAbstraction类
class RefinedAbstraction : public Abstraction
{
public:
void Operation() override
{
implementor->Operation();
}
};
客户端实现
int main()
{
Abstraction * ab = new RefinedAbstraction();
ab->SetImplementor(new ConcreteImplementorA());
ab->Operation();
free (ab);
ab->SetImplementor(new ConcreteImplementorB());
ab->Operation();
}
运行结果
具体实现A的方法执行
具体实现B的方法执行