文章目錄
- 概述
- 原理
- 結構圖
- 代碼示例
- 小結
概述
橋接模式(bridge pattern) 的定義是:將抽象部分與它的實現部分分離,使它們都可以獨立地變化。
橋接模式用一種巧妙的方式處理多層繼承存在的問題,用抽象關聯來取代傳統的多層繼承,將類之間的靜態繼承關系轉變為動態的組合關系,使得系統更加靈活,并易于擴展,有效的控制了系統中類的個數 (避免了繼承層次的指數級爆炸).
原理
橋接(Bridge)模式包含以下主要角色:
- 抽象化(Abstraction)角色 :主要負責定義出該角色的行為 ,并包含一個對實現化對象的引用。
- 擴展抽象化(RefinedAbstraction)角色 :是抽象化角色的子類,實現父類中的業務方法,并通過組合關系調用實現化角色中的業務方法。
- 實現化(Implementor)角色 :定義實現化角色的接口,包含角色必須的行為和屬性,并供擴展抽象化角色調用。
- 具體實現化(Concrete Implementor)角色 :給出實現化角色接口的具體實現。
結構圖
代碼示例
來看下代碼示例吧,如下圖:
// Implementor.h
#ifndef IMPLEMENTOR_H
#define IMPLEMENTOR_Hclass Implementor {
public:virtual ~Implementor() {}virtual void OperationImpl() = 0;
};#endif // IMPLEMENTOR_H
// ConcreteImplementorA.h
#ifndef CONCRETEIMPLEMENTORA_H
#define CONCRETEIMPLEMENTORA_H#include "Implementor.h"class ConcreteImplementorA : public Implementor {
public:void OperationImpl() override {// Concrete implementation Astd::cout << "Concrete Implementor A" << std::endl;}
};#endif // CONCRETEIMPLEMENTORA_H
// ConcreteImplementorB.h
#ifndef CONCRETEIMPLEMENTORB_H
#define CONCRETEIMPLEMENTORB_H#include "Implementor.h"class ConcreteImplementorB : public Implementor {
public:void OperationImpl() override {// Concrete implementation Bstd::cout << "Concrete Implementor B" << std::endl;}
};
// Abstraction.h
#ifndef ABSTRACTION_H
#define ABSTRACTION_H#include "Implementor.h"class Abstraction {
protected:Implementor* implementor;public:Abstraction(Implementor* implementor) : implementor(implementor) {}virtual ~Abstraction() { delete implementor; }virtual void Operation() = 0;
};
/ RefinedAbstraction.h
#ifndef REFINEDABSTRACTION_H
#define REFINEDABSTRACTION_H#include "Abstraction.h"class RefinedAbstraction : public Abstraction {
public:RefinedAbstraction(Implementor* implementor) : Abstraction(implementor) {}void Operation() override {// Refined operationstd::cout << "Refined Abstraction" << std::endl;implementor->OperationImpl();}
};
/ main.cpp
#include <iostream>
#include "Abstraction.h"
#include "ConcreteImplementorA.h"
#include "ConcreteImplementorB.h"
#include "RefinedAbstraction.h"int main() {ConcreteImplementorA* implementorA = new ConcreteImplementorA();ConcreteImplementorB* implementorB = new ConcreteImplementorB();Abstraction* abstractionA = new RefinedAbstraction(implementorA);Abstraction* abstractionB = new RefinedAbstraction(implementorB);abstractionA->Operation();abstractionB->Operation();delete abstractionA;delete abstractionB;return 0;
}
小結
上邊有橋接模式的概述,原理,以及代碼示例。看起來不錯吧,感興趣,可以一起學習學習。