版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/ouyangshima/article/details/8482886
Bridge桥接模式
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
解析
1.Abastrction:某个抽象类,它的实现方式有Implementor完成
2.Implementor:实现类的抽象基类,定义了实现Abstraction的基本操作,而它的派生类实现这些接口
3.Implementor::OperationImp:定义了为实现Abstract需要的基本操作,有Implementor的派生类实现,而在Abstraction::operation函数中根据不同的指针多态调用这个函数
Bridge用于将表示和实现解耦,两者可以独立的变化。在Abstraction类中维护一个Implementor类指针,需要采用不同的实现方式的时候只需要传入不同的Implementor派生类就可以了。
Bridge的实现方式其实和Builder十分相近,可以这么说:本质上是一样的,只是封装的东西不一样罢了。
两者的实现都有如下的共同点:
- 抽象出来一个基类,这个基类里面定义了共有的一些行为,形成接口函数(对接口编程而不是对实现编程),这个接口函数在Builder中是BuilderPart函数,在Bridge模式中是OperationImp函数。
- 其次,聚合一个基类的指针,如Builder模式中Director类聚合了一个Builder基类的指针,而Bridge模式中Abstraction类聚合了一个Implementor基类的指针(优先采用聚合而不是继承)。
- 而在使用的时候,都把对这个类的使用封装在一个函数中,在Builder中是封装在Director::Construct函数中,因为装配不同部分的过程是一致的,而在Bridge模式中则是封装在Abstraction::Operation函数中,在这个函数中调用调用对应的Implementor::operationImp函数。
- 就这两个模式而言,Builder封装了不同的生成组成部分的方式,而Bridge模式封装了不同的实现方式。因此,如果以一些最基本的面向对象的设计原则来分析这些模式的实现的话,还是可以看到很多共同的地方的。
小demo
bridge.h
- #ifndef BRIDEG_H
- #define BRIDEG_H
- class Implementor;
- // 维护一个Implementor类的指针
- class Abstraction
- {
- public:
- Abstraction(Implementor* pImplementor);
- virtual ~Abstraction();
- void Operation();
- protected:
- Implementor* m_pImplementor;
- };
- // 为实现Abstraction定义的抽象基类,定义了实现的接口函数
- class Implementor
- {
- public:
- Implementor(){}
- virtual ~Implementor(){}
- virtual void OperationImpl() = 0;
- };
- // 继承自Implementor,是Implementor的不同实现之一
- class ConcreateImplementorA : public Implementor
- {
- public:
- ConcreateImplementorA(){}
- virtual ~ConcreateImplementorA(){}
- virtual void OperationImpl();
- };
- // 继承自Implementor,是Implementor的不同实现之一
- class ConcreateImplementorB : public Implementor
- {
- public:
- ConcreateImplementorB(){}
- virtual ~ConcreateImplementorB(){}
- virtual void OperationImpl();
- };
- #endif
bridge.cpp
- #include "Brige.h"
- #include <iostream>
- void ConcreateImplementorA::OperationImpl()
- {
- std::cout << "Implementation by ConcreateImplementorA\n";
- }
- void ConcreateImplementorB::OperationImpl()
- {
- std::cout << "Implementation by ConcreateImplementorB\n";
- }
- Abstraction::Abstraction(Implementor* pImplementor) : m_pImplementor(pImplementor)
- {
- }
- Abstraction::~Abstraction()
- {
- delete m_pImplementor;
- m_pImplementor = NULL;
- }
- void Abstraction::Operation()
- {
- m_pImplementor->OperationImpl();
- }
main.cpp
- #include "Brige.h"
- #include <stdlib.h>
- #include <stdio.h>
- int main()
- {
- Implementor *pImplA = new ConcreateImplementorA();
- Abstraction *pAbstraction1 = new Abstraction(pImplA);
- pAbstraction1->Operation();
- Implementor *pImplB = new ConcreateImplementorB();
- Abstraction *pAbstraction2 = new Abstraction(pImplB);
- pAbstraction2->Operation();
- delete pAbstraction1;
- delete pAbstraction2;
- system("pause");
- return 0;
- }