1. 桥接模式: 将抽象部分与它的实现部分分离,使它们都可以独立的变化。
分离是指 抽象类和它的派生类用来实现自己的对象分离。
实现系统可以有多角度分类,每一种分类都有可能变化,那么把这种多角度分离出来让他们独立变化,减少他们之间的耦合。
实例:
implementor.h implementor.cpp 实现接口
#ifndef IMPLEMENTOR_H #define IMPLEMENTOR_H class Implementor { public: Implementor(); void virtual operation()=0; }; #endif // IMPLEMENTOR_H
#include "implementor.h" Implementor::Implementor() { }
concreteimplementora.h concreteimplementora.cpp 具体实现功能A
#ifndef CONCRETEIMPLEMENTORA_H #define CONCRETEIMPLEMENTORA_H #include "implementor.h" class ConcreteImplementorA : public Implementor { public: ConcreteImplementorA(); void operation(); }; #endif // CONCRETEIMPLEMENTORA_H
#include "concreteimplementora.h" #include <stdio.h> ConcreteImplementorA::ConcreteImplementorA() { } void ConcreteImplementorA::operation() { printf("ConcreteImplementorA operation "); }
concreteimplementorb concreteimplementorb 具体实现功能B
#ifndef CONCRETEIMPLEMENTORB_H #define CONCRETEIMPLEMENTORB_H #include "implementor.h" class ConcreteImplementorB : public Implementor { public: ConcreteImplementorB(); void operation(); }; #endif // CONCRETEIMPLEMENTORB_H
#include "concreteimplementorb.h" #include <stdio.h> ConcreteImplementorB::ConcreteImplementorB() { } void ConcreteImplementorB::operation() { printf("ConcreteImplementorB operation "); }
abstraction.h abstraction.cpp 抽象
#ifndef ABSTRACTION_H #define ABSTRACTION_H #include "implementor.h" class Abstraction { public: Abstraction(); void setImplementor(Implementor *implementor); void virtual operation(); protected: Implementor *implementor; }; #endif // ABSTRACTION_H
#include "abstraction.h" Abstraction::Abstraction() { implementor = 0; } void Abstraction::setImplementor(Implementor *implementor) { this->implementor = implementor; } void Abstraction::operation() { implementor->operation(); }
refinedabstraction.h refinedabstraction.cpp 精确抽象
#ifndef REFINEDABSTRACTION_H #define REFINEDABSTRACTION_H #include "abstraction.h" class RefinedAbstraction : public Abstraction { public: RefinedAbstraction(); void operation(); }; #endif // REFINEDABSTRACTION_H
#include "refinedabstraction.h" RefinedAbstraction::RefinedAbstraction() { } void RefinedAbstraction::operation() { implementor->operation(); }
main.cpp
#include <iostream> #include "refinedabstraction.h" #include "concreteimplementora.h" #include "concreteimplementorb.h" using namespace std; int main() { cout << "Bridge test!" << endl; Abstraction *ab = new RefinedAbstraction(); ab->setImplementor(new ConcreteImplementorA()); ab->operation(); ab->setImplementor(new ConcreteImplementorB()); ab->operation(); return 0; }