设计模式精解: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.mzph.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;在文本编辑方面有着…