桥接模式:把事物对象和其详细行为、详细特征分离开来,使它们能够各自独立的变化。事物对象仅是一个抽象的概念。如“圆形”、“三角形”归于抽象的“形状”之下,而“画圆”、“画三角”归于实现行为的“绘图”类之下,然后由“形状”调用“绘图”。“形状”成为一个继承体系,“绘图”成为还有一个继承体系,抽象和实现两者的关系为聚合关系。UML图例如以下:
#include <iostream> #include <string> using namespace std; // 实现 class Implementor { public: virtual void Operation() = 0; }; // 详细实现A class ConcreteImplementorA : public Implementor { public: void Operation() { cout << "运行详细实现A中的方法" << endl; } }; // 详细实现B class ConcreteImplementorB : public Implementor { public: void Operation() { cout << "运行详细实现B中的方法" << endl; } }; // 抽象 class Abstraction { public: void SetImplementor(Implementor *i) { implementor = i; } virtual void Operation() = 0; ~Abstraction() { delete implementor; } protected: Implementor *implementor; // 包括一个实现 }; // 被提炼的抽象 class RefineAbstraction : public Abstraction { public: void Operation() { implementor->Operation(); } }; int main() { Abstraction *ab = new RefineAbstraction(); ab->SetImplementor(new ConcreteImplementorA()); ab->Operation(); ab->SetImplementor(new ConcreteImplementorB()); ab->Operation(); // 别忘记删除指针 delete ab; system("pause"); return 0; }
当须要加入抽象时,仅仅须要继承Abstraction就可以。当须要加入详细实现时,继承Implementor就可以。
这样既减少了耦合度。也符合开放-封闭原则,即:功能的扩充不须要改动原来的代码而仅仅须要加入所需新的代码。
原文:http://www.cnblogs.com/mengfanrong/p/5222347.html