C++ Bridge 设计模式
Bridge模式是应用最广泛也是我个人比较喜欢的一个C++设计模式之一。
Bridge模式意图:降低抽象和实现之间的耦合。
面向对象系统设计和分析中最重要的一点就是:高内聚,低耦合。Bridge模式使得抽象和实现能够相对独立。
Bridge模式结构图:
Bridge模式的关键在于Abstraction的派生类中维护了一个纸箱Implementor类的指针。
让Implentor的派生类来去实现。从而实现了抽象和实现的相对独立。
参考代码:
#pragma once //Abstraction.h class Abstraction { public: Abstraction(void){}; virtual ~Abstraction(void){}; virtual void Operation() = 0; };
#pragma once //Implementor.h class Implementor { public: Implementor(void){}; virtual ~Implementor(void){}; virtual void OperationImp() = 0; };
#pragma once //ConcreteImplementorA.h #include "implementor.h" class ConcreteImplementorA : public Implementor { public: ConcreteImplementorA(void); ~ConcreteImplementorA(void); void OperationImp(); };
#pragma once //ConcreteImplementorB.h #include "implementor.h" class ConcreteImplementorB : public Implementor { public: ConcreteImplementorB(void); ~ConcreteImplementorB(void); void OperationImp(); };
#pragma once //RefinedAbstraction.h #include "abstraction.h" #include "Implementor.h" class Implementor; class RefinedAbstraction : public Abstraction { public: RefinedAbstraction(void); RefinedAbstraction(Implementor *imp); ~RefinedAbstraction(void); void Operation(); private: Implementor *m_imp; };
#include <iostream> #include "ConcreteImplementorA.h" using namespace std; //ConcreteImplementonA.cpp ConcreteImplementorA::ConcreteImplementorA(void) { } ConcreteImplementorA::~ConcreteImplementorA(void) { } void ConcreteImplementorA::OperationImp() { cout << "Hi, I am in ConcreteImplementorA" << endl; }
#include <iostream> #include "ConcreteImplementorB.h" using namespace std; //ConcreteImplementorB.cpp ConcreteImplementorB::ConcreteImplementorB(void) { } ConcreteImplementorB::~ConcreteImplementorB(void) { } void ConcreteImplementorB::OperationImp() { cout << "Hi, I am in ConcreteImplementorB" << endl; }
#include <iostream> #include "RefinedAbstraction.h" using namespace std; //RefinedAbstraction.cpp RefinedAbstraction::RefinedAbstraction(void) { m_imp = NULL; } RefinedAbstraction::~RefinedAbstraction(void) { } RefinedAbstraction::RefinedAbstraction(Implementor *imp) { m_imp = imp; } void RefinedAbstraction::Operation() { m_imp->OperationImp(); }
#include "Abstraction.h" #include "ConcreteImplementorA.h" #include "ConcreteImplementorB.h" #include "RefinedAbstraction.h" //main.cpp int main() { ConcreteImplementorA *pImpA = new ConcreteImplementorA; ConcreteImplementorB *pImpB = new ConcreteImplementorB; Abstraction *objA = new RefinedAbstraction(pImpA); Abstraction *objB = new RefinedAbstraction(pImpB); objA->Operation(); objB->Operation(); }
我个人 非常欣赏也非常推崇Bridge模式。