23种设计模式C++源码与UML实现--桥接模式
生活随笔
收集整理的這篇文章主要介紹了
23种设计模式C++源码与UML实现--桥接模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
橋接模式
Bridge模式,又叫做橋接模式,是構造型的設計模式之一。Bridge模式基于類的最小設計原則,通過使用封裝,聚合以及繼承等行為讓類承擔不同的責任。它的主要特點是把抽象(Abstraction)與行為實現(implementation)分離開來,從而可以保持各部分的獨立性以及對它們的功能擴展。
UML實現如下:
client
Bridge模式的使用者
Abstration
抽象類接口(接口或抽象類)維護對行為實現(Implementor)的引用
Refined Abstraction
Abstracton子類
Implementor
行為實現類接口(Abstraction接口定義了基于Implementor接口的更高層次的操作)
ConcreteImplementor
Implementor子類
橋接模式,適用于將抽象部分與實體部分分離(解耦合),使它們可以獨立變化。
橋接模式代碼實現:
// // Created by andrew on 2020/11/17. // #include <iostream>using namespace std;class Engine { public:virtual void InstallEngine() = 0;virtual ~Engine() {} };class Engine4400cc : public Engine { public:virtual void InstallEngine() {cout << "I'm 4400cc install over." << endl;} };class Engine4500cc : public Engine { public:virtual void InstallEngine() {cout << "I'm 4500cc install over." << endl;} };class Car { public:Car(Engine *engine) {m_engine = engine;}virtual ~Car() {}protected:Engine *m_engine; };class BMW3 : public Car { public:BMW3(Engine *engine) : Car(engine) {}// 具體實現和car分離 // m_engine每個car都要有個引擎,抽象出來,放到公共類中,實現抽象和實現分離virtual void intallEngine() {//安裝的動作是在engine里面實現,與car分離m_engine->InstallEngine();} };class BMW5 : public Car { public:BMW5(Engine *engine) : Car(engine) {}virtual void installEngine() {cout << "BMW5" << endl;m_engine->InstallEngine();} };int main(int argc, char *argv[]) {Engine *engine = NULL;BMW5 *bmw5 = NULL;engine = new Engine4400cc;bmw5 = new BMW5(engine);bmw5->installEngine();delete bmw5;delete engine;return 0; }總結
以上是生活随笔為你收集整理的23种设计模式C++源码与UML实现--桥接模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 23种设计模式C++源码与UML实现--
- 下一篇: rabbitmq rpc