設計模式精解:GoF 23種設計模式全解析

在軟件工程中,設計模式是為了解決常見的軟件設計問題而形成的一套經典解決方案。這些模式不僅能夠幫助開發者提高設計的靈活性和代碼的重用性,還能使問題的解決方案更加清晰、易于理解。《設計模式精解-GoF 23種設計模式》一書中所列舉的23種設計模式,是由四位作者(即GoF,Gang of Four)提出的,至今仍被廣泛應用在各種軟件開發項目中。本文將對這些設計模式進行全面解析,每種模式均配以C++代碼示例,旨在為讀者提供一個清晰、系統的學習路徑。

創建型模式(Creational Patterns)

創建型模式涉及對象的創建機制,旨在創建對象時增加系統的靈活性和效率。

工廠模式(Factory Pattern)

工廠模式通過定義一個用于創建對象的接口,讓子類決定實例化哪一個類。這樣的方式允許在不明確指定具體類的情況下創建對象。

class Product {
public:virtual ~Product() {}virtual std::string Operation() const = 0;
};class ConcreteProduct1 : public Product {
public:std::string Operation() const override {return "Result of ConcreteProduct1";}
};class Creator {
public:virtual ~Creator(){}virtual Product* FactoryMethod() const = 0;std::string SomeOperation() const {Product* product = this->FactoryMethod();std::string result = "Creator: The same creator's code has just worked with " + product->Operation();delete product;return result;}
};

抽象工廠模式(Abstract Factory Pattern)

抽象工廠模式提供一個接口,用于創建相關或依賴對象的家族,而不需要明確指定具體類。

class AbstractProductA {
public:virtual ~AbstractProductA(){};virtual std::string UsefulFunctionA() const = 0;
};class AbstractProductB {
public:virtual ~AbstractProductB(){};virtual std::string UsefulFunctionB() const = 0;virtual std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const = 0;
};class ConcreteProductA1 : public AbstractProductA {
public:std::string UsefulFunctionA() const override {return "The result of the product A1.";}
};class ConcreteProductB1 : public AbstractProductB {
public:std::string UsefulFunctionB() const override {return "The result of the product B1.";}std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const override {const std::string result = collaborator.UsefulFunctionA();return "The result of the B1 collaborating with ( " + result + " )";}
};

單例模式(Singleton Pattern)

單例模式確保一個類只有一個實例,并提供一個全局訪問點。

class Singleton {
protected:Singleton(const std::string value): value_(value) {}static Singleton* singleton_;std::string value_;public:Singleton(Singleton &other) = delete;void operator=(const Singleton &) = delete;static Singleton *GetInstance(const std::string& value);std::string value() const{return value_;} 
};Singleton* Singleton::singleton_ = nullptr;;Singleton *Singleton::GetInstance(const std::string& value) {if(singleton_ == nullptr){singleton_ = new Singleton(value);}return singleton_;
}

建造者模式(Builder Pattern)

建造者模式使用多個簡單的對象一步一步構建成一個復雜的對象。

class Product1 {
public:std::vector<std::string> parts_;void ListParts()const {std::cout << "Product parts: ";for (size_t i = 0; i < parts_.size(); i++) {if (parts_[i] == parts_.back()) {std::cout << parts_[i];} else {std::cout << parts_[i] << ", ";}}std::cout << "\n\n";}
};class Builder {
public:virtual ~Builder() {}virtual void ProducePartA() const = 0;virtual void ProducePartB() const = 0;virtual void ProducePartC() const = 0;
};class ConcreteBuilder1 : public Builder {
private:Product1* product;public:ConcreteBuilder1() {this->Reset();}~ConcreteBuilder1() {delete product;}void Reset() {this->product = new Product1();}void ProducePartA()const override {this->product->parts_.push_back("PartA1");}void ProducePartB()const override {this->product->parts_.push_back("PartB1");}void ProducePartC()const override {this->product->parts_.push_back("PartC1");}Product1* GetProduct() {Product1* result = this->product;this->Reset();return result;}
};

原型模式(Prototype Pattern)

原型模式使用原型實例指定創建對象的種類,并且通過拷貝這些原型創建新的對象。

class Prototype {
protected:std::string prototype_name_;float prototype_field_;public:Prototype() {}Prototype(std::string prototype_name): prototype_name_(prototype_name) {}virtual ~Prototype() {}virtual Prototype *clone() const = 0;virtual void Method(float prototype_field) {this->prototype_field_ = prototype_field;std::cout << "Call Method from " << this->prototype_name_ << " with field : " << this->prototype_field_ << std::endl;}
};class ConcretePrototype1 : public Prototype {
private:float concrete_prototype_field1_;public:ConcretePrototype1(std::string prototype_name, float concrete_prototype_field): Prototype(prototype_name), concrete_prototype_field1_(concrete_prototype_field) {}Prototype *clone() const override {return new ConcretePrototype1(*this);}
};class ConcretePrototype2 : public Prototype {
private:float concrete_prototype_field2_;public:ConcretePrototype2(std::string prototype_name, float concrete_prototype_field): Prototype(prototype_name), concrete_prototype_field2_(concrete_prototype_field) {}Prototype *clone() const override {return new ConcretePrototype2(*this);}
};

結構型模式(Structural Patterns)

結構型模式關注于對象組合,它們利用繼承和接口的方式來組合接口或實現以提供新的功能。

橋接模式(Bridge Pattern)

橋接模式通過將抽象部分與實現部分分離,使它們可以獨立變化。

class Implementation {
public:virtual ~Implementation() {}virtual std::string OperationImplementation() const = 0;
};class ConcreteImplementationA : public Implementation {
public:std::string OperationImplementation() const override {return "ConcreteImplementationA: Here's the result on the platform A.\n";}
};class ConcreteImplementationB : public Implementation {
public:std::string OperationImplementation() const override {return "ConcreteImplementationB: Here's the result on the platform B.\n";}
};class Abstraction {
protected:Implementation* implementation_;public:Abstraction(Implementation* implementation) : implementation_(implementation) {}virtual ~Abstraction() {}virtual std::string Operation() const {return "Abstraction: Base operation with:\n" +this->implementation_->OperationImplementation();}
};class ExtendedAbstraction : public Abstraction {
public:ExtendedAbstraction(Implementation* implementation) : Abstraction(implementation) {}std::string Operation() const override {return "ExtendedAbstraction: Extended operation with:\n" + this->implementation_->OperationImplementation();}
};

適配器模式(Adapter Pattern)

適配器模式允許不兼容的接口之間的通信,它通過將一個類的接口轉換成客戶期望的另一個接口來實現。

class Target {
public:virtual ~Target() {}virtual std::string Request() const {return "Target: The default target's behavior.";}
};class Adaptee {
public:std::string SpecificRequest() const {return ".eetpadA eht fo roivaheb laicepS";}
};class Adapter : public Target {
private:Adaptee* adaptee_;public:Adapter(Adaptee* adaptee) : adaptee_(adaptee) {}std::string Request() const override {std::string to_reverse = this->adaptee_->SpecificRequest();std::reverse(to_reverse.begin(), to_reverse.end());return "Adapter: (TRANSLATED) " + to_reverse;}
};

裝飾器模式(Decorator Pattern)

裝飾器模式允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,因為這種模式通過創建一個裝飾類來包裝原有的類。

class Component {
public:virtual ~Component() {}virtual std::string Operation() const = 0;
};class ConcreteComponent : public Component {
public:std::string Operation() const override {return "ConcreteComponent";}
};class Decorator : public Component {
protected:Component* component_;public:Decorator(Component* component) : component_(component) {}std::string Operation() const override {return this->component_->Operation();}
};class ConcreteDecoratorA : public Decorator {
public:ConcreteDecoratorA(Component* component) : Decorator(component) {}std::string Operation() const override {return "ConcreteDecoratorA(" + Decorator::Operation() + ")";}
};class ConcreteDecoratorB : public Decorator {
public:ConcreteDecoratorB(Component* component) : Decorator(component) {}std::string Operation() const override {return "ConcreteDecoratorB(" + Decorator::Operation() + ")";}
};

組合模式(Composite Pattern)

組合模式允許將對象組合成樹形結構以表示“部分-整體”的層次結構。組合模式使得用戶對單個對象和組合對象的使用具有一致性。

class Component {
protected:Component* parent_;public:virtual ~Component() {}void SetParent(Component* parent) {this->parent_ = parent;}Component* GetParent() const {return this->parent_;}virtual void Add(Component* component) {}virtual void Remove(Component* component) {}virtual bool IsComposite() const {return false;}virtual std::string Operation() const = 0;
};class Leaf : public Component {
public:std::string Operation() const override {return "Leaf";}
};class Composite : public Component {
protected:std::list<Component*> children_;public:void Add(Component* component) override {this->children_.push_back(component);component->SetParent(this);}void Remove(Component* component) override {children_.remove(component);component->SetParent(nullptr);}bool IsComposite() const override {return true;}std::string Operation() const override {std::string result;for (const Component* c : children_) {if (c == children_.back()) {result += c->Operation();} else {result += c->Operation() + "+";}}return "Branch(" + result + ")";}
};

享元模式(Flyweight Pattern)

享元模式是對象池的一種實現,它用于減少創建對象的數量,以減少內存占用和提高性能。這種類型的設計模式屬于結構型模式,因為該模式提供了減少對象數量從而改善應用所需的對象結構的方式。

class Flyweight {
protected:std::string shared_state_;public:Flyweight(const std::string& shared_state) : shared_state_(shared_state) {}virtual ~Flyweight() {}virtual void Operation(const std::string& unique_state) const {std::cout << "Flyweight: Displaying shared (" << this->shared_state_ << ") and unique (" << unique_state << ") state.\n";}
};class FlyweightFactory {
private:std::unordered_map<std::string, Flyweight*> flyweights_;std::string GetKey(const std::vector<std::string>& state) const {std::string key;for (const std::string& s : state) {key += s;}return key;}public:FlyweightFactory(const std::vector<std::string>& initial_flyweights) {for (const std::string& state : initial_flyweights) {this->flyweights_.insert(std::make_pair<std::string, Flyweight*>(this->GetKey({state}), new Flyweight(state)));}}~FlyweightFactory() {for (auto pair : this->flyweights_) {delete pair.second;}this->flyweights_.clear();}Flyweight* GetFlyweight(const std::vector<std::string>& shared_state) {std::string key = this->GetKey(shared_state);if (this->flyweights_.find(key) == this->flyweights_.end()) {std::cout << "FlyweightFactory: Can't find a flyweight, creating new one.\n";this->flyweights_.insert(std::make_pair(key, new Flyweight(key)));} else {std::cout << "FlyweightFactory: Reusing existing flyweight.\n";}return this->flyweights_.at(key);}void ListFlyweights() const {size_t count = this->flyweights_.size();std::cout << "\nFlyweightFactory: I have " << count << " flyweights:\n";for (auto pair : this->flyweights_) {std::cout << pair.first << "\n";}}
};

外觀模式(Facade Pattern)

外觀模式提供了一個統一的接口,用來訪問子系統中的一群接口。外觀定義了一個高層接口,讓子系統更容易使用。

class Subsystem1 {
public:std::string Operation1() const {return "Subsystem1: Ready!\n";}std::string OperationN() const {return "Subsystem1: Go!\n";}
};class Subsystem2 {
public:std::string Operation1() const {return "Subsystem2: Get ready!\n";}std::string OperationZ() const {return "Subsystem2: Fire!\n";}
};class Facade {
protected:Subsystem1* subsystem1_;Subsystem2* subsystem2_;public:Facade(Subsystem1* subsystem1 = nullptr,Subsystem2* subsystem2 = nullptr) {

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/718490.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/718490.shtml
英文地址,請注明出處:http://en.pswp.cn/news/718490.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

微信小程序的單位

在小程序開發中&#xff0c;rpx是一種相對長度單位&#xff0c;用于在不同設備上實現自適應布局。它是微信小程序特有的單位&#xff0c;表示屏幕寬度的 1/750。 rpx單位的好處在于可以根據設備的屏幕寬度進行自動換算&#xff0c;使得頁面在不同設備上保持一致的顯示效果。例…

學習筆記 前端

學習筆記 前端 學習記錄nodejsyarn解決方法 學習記錄 nodejs yarn 描述&#xff1a;想體驗一下chatgptnextweb在本地部署&#xff0c;但是本地部署需要yarn環境&#xff0c;網上看了yarn在node16以上就自帶了&#xff0c;而我的電腦是node18&#xff0c;所以就直接輸入了ya…

(十)SpringCloud系列——openfeign的高級特性實戰內容介紹

前言 本節內容主要介紹一下SpringCloud組件中微服務調用組件openfeign的一些高級特性的用法以及一些常用的開發配置&#xff0c;如openfeign的超時控制配置、openfeign的重試機制配置、openfeign集成高級的http客戶端、openfeign的請求與響應壓縮功能&#xff0c;以及如何開啟…

論文閱讀-高效構建檢查點

論文標題&#xff1a;On Efficient Constructions of Checkpoints 摘要 高效構建檢查點/快照是訓練和診斷深度學習模型的關鍵工具。在本文中&#xff0c;我們提出了一種適用于檢查點構建的有損壓縮方案&#xff08;稱為LC-Checkpoint&#xff09;。LC-Checkpoint同時最大化了…

MFC中CString的MakeUpper使用方法

在MFC中&#xff0c;CString類提供了MakeUpper函數來將字符串中的字符全部轉換為大寫。MakeUpper函數沒有參數&#xff0c;它會直接修改原始的CString對象。 下面是一些示例代碼&#xff0c;演示了如何使用MakeUpper函數&#xff1a; CString str "Hello, World!"…

uniapp開發android原生插件

一、下載原生開發SDK Android 離線SDK - 正式版 | uni小程序SDK (dcloud.net.cn)、 https://nativesupport.dcloud.net.cn/AppDocs/download/android.html 將開發uniappa原生android的插件解壓到ben本地目錄&#xff0c;目錄結構如下&#xff1a; 接下就可以使用 UniPlugin-Hel…

【本科組冠名獎】2023年第八屆數維杯數學建模挑戰賽獲獎感言

美國大學生數學建模競賽已結束過半&#xff0c;現在又迎來了2024年第九屆數維杯國賽&#xff0c;準備參加今年數維杯國賽的同學&#xff0c;今天我們一起看看去年優秀的選手都有什么獲獎感言吧~希望能幫到更多熱愛數學建模的同學。據說文末在看點贊的大佬都會直沖國獎呢&#x…

實用Pycharm插件

Pycharm的離線安裝&#xff1a;https://plugins.jetbrains.com/ 需要根據對應的Pycharm/Goland版本選取所需的 對于實用的插件如下&#xff1a; 實時查看每一行的git blame信息&#xff1a; Gittoolbox 轉換IDE的英文為中文&#xff1a;Chinese IDE側格式化json字符串&#…

UE5 C++ TPS開發 學習記錄(八

這一次到了p19 完善了UI和寫了創建房間 MultiPlayerSessionSubsystem.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Subsystems/GameInstanceSubsystem.h" #in…

python基礎-基本數據類型深入-2.2

目錄 集合 集合的定義 集合操作 集合的內建函數 集合與內置函數 集合練習-1 集合練習-2 集合練習-3 集合 集合的定義 學習關于 Python 集的所有內容&#xff1b;如何創建它們、添加或刪除其中的元素&#xff0c;以及在 Python 中對集合執行的所有操作。 Python 中的集…

掌握Go語言:探索Go語言中的變量,靈活性與可讀性的完美結合(4)

想要編寫簡潔高效的Go語言代碼嗎&#xff1f;掌握變量的使用是關鍵&#xff01;Go語言的變量聲明方式多樣&#xff0c;包括var關鍵字和短變量聲明&#xff0c;同時支持類型推斷&#xff0c;讓代碼更加清晰易讀。 變量聲明方式 在Go語言中&#xff0c;變量的聲明方式有兩種&am…

少兒編程 中國電子學會C++等級考試一級歷年真題答案解析【持續更新 已更新82題】

C 等級考試一級考綱說明 一、能力目標 通過本級考核的學生&#xff0c;能對 C 語言有基本的了解&#xff0c;會使用順序結構、選擇結構、循環結構編寫程序&#xff0c;具體用計算思維的方式解決簡單的問題。 二、考核目標 考核內容是根據軟件開發所需要的技能和知識&#x…

Leetcode 3071. Minimum Operations to Write the Letter Y on a Grid

Leetcode 3071. Minimum Operations to Write the Letter Y on a Grid 1. 解題思路2. 代碼實現 題目鏈接&#xff1a;3071. Minimum Operations to Write the Letter Y on a Grid 1. 解題思路 這一題思路上也是比較直接的&#xff0c;就是首先找到這個Y字符&#xff0c;然后…

單詞規律00

題目鏈接 單詞規律 題目描述 注意點 pattern只包含小寫英文字母s只包含小寫英文字母和 ’ ’s不包含任何前導或尾隨對空格s中每個單詞都被 單個空格 分隔 解答思路 本題與上一次同構字符串類似&#xff0c;思路可以參照同構字符串 代碼 class Solution {public boolean …

工作流/任務卸載相關開源論文分享

decima-sim 概述&#xff1a; 圖神經網絡強化學習處理多工作流 用的spark的仿真環境&#xff0c;mit的論文&#xff0c;價值很高&#xff0c;高被引&#xff1a;663倉庫地址&#xff1a;https://github.com/hongzimao/decima-sim論文&#xff1a;https://web.mit.edu/decima/co…

企業財務規劃的未來:自動化智能化如何推動全面預算管理

隨著自動化和智能化對企業的影響日益明顯&#xff0c;了解和接受那些有可能改變企業財務規劃的技術變得愈發重要。新興技術是推動企業增長和業務生產的中堅力量。作為企業財務專業人員&#xff0c;熟悉技術能夠幫助他們了解企業的未來價值&#xff0c;從而更好的領導團隊。數智…

springboot支持的常用日志框架介紹

日志系統是計算機系統中用于記錄和跟蹤事件、錯誤和信息的軟件組件。在軟件開發和維護過程中&#xff0c;日志系統起著至關重要的作用。它可以幫助開發人員了解軟件的運行情況&#xff0c;快速定位和解決問題。本文將從以下幾個方面介紹日志系統&#xff1a;日志系統概述、Spri…

Mybatis plus拓展功能-枚舉處理器

目錄 1 前言 2 使用方法 2.1 在application.yml中添加配置 2.2 定義枚舉類 2.3 在實體類和賦值時中使用 1 前言 在我們的開發過程中&#xff0c;常常需要用一些數字來表示狀態。比如說&#xff1a;1-正常&#xff0c;0-凍結。然而這樣并不能做到見名知意&#xff0c;特別是…

HTML最強入門學習筆記+GitHub小項目源碼

HTML學習筆記 GitHub項目鏈接: 點我跳轉GitHub 本博客采用markdown編寫&#xff0c;上面這個鏈接跳轉就是采用了html的<a></a>的代碼設計的跳轉提示~ 1.創建文件可以使用 ! 在VSCode中進行快速補全從而生成一整個HTML結構 HTML組成 <!DOCTYPE html><htm…

vscode——遠端配置及一些問題解決

vscode——遠端配置 安裝Remote -SSH插件配置config本地變化一些問題缺失核心關閉vscode自動更新 嘗試寫入管道不存在hostname -I 查出來的ip連不上 我們之前大概了解了vscode的本地設置&#xff0c;我們之前提過&#xff0c;vscode是一款編輯器&#xff0c;在文本編輯方面有著…