当前位置: 首页 > news >正文

【设计模式】【结构型模式(Structural Patterns)】之装饰模式(Decorator Pattern)

1. 设计模式原理说明

装饰模式(Decorator Pattern) 是一种结构型设计模式,它允许在不改变对象接口的前提下,动态地给对象增加额外的责任或功能。这种模式创建了一个装饰类,用于包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

主要角色
  1. Component(组件):定义了一个对象接口,可以给这些对象动态地添加职责。
  2. ConcreteComponent(具体组件):定义了一个具体的对象,也可以给这个对象添加一些责任。
  3. Decorator(装饰器):持有一个 Component 对象的实例,并定义了一个与 Component 接口一致的接口。
  4. ConcreteDecorator(具体装饰器):向组件添加新的责任,通常通过在其前后添加行为来实现。

2. UML 类图及解释

UML 类图
+-----------------+                +-----------------+
|    Component    |                | ConcreteComponent|
|-----------------|                |-----------------|
| + operation(): void|             | + operation(): void|
+-----------------+                +-----------------+^                             ^|                             ||                             |v                             v
+-----------------+
|    Decorator    |
|-----------------|
| - component: Component  |
| + setComponent(component: Component)|
| + operation(): void            |
+-----------------+^||v
+-----------------+                +-----------------+
| ConcreteDecoratorA|             | ConcreteDecoratorB|
|-----------------|                |-----------------|
| + operation(): void|             | + operation(): void|
| + addedBehavior(): void|         | + addedBehavior(): void|
+-----------------+                +-----------------+
类图解释
  • Component:定义了一个对象接口,可以给这些对象动态地添加职责。
  • ConcreteComponent:定义了一个具体的对象,也可以给这个对象添加一些责任。
  • Decorator:持有一个 Component 对象的实例,并定义了一个与 Component 接口一致的接口。装饰器可以在其前后添加行为。
  • ConcreteDecoratorA 和 ConcreteDecoratorB:具体装饰器,向组件添加新的责任,通常通过在其前后添加行为来实现。

3. 代码案例及逻辑详解

Java 代码案例
// 组件接口
interface Component {void operation();
}// 具体组件
class ConcreteComponent implements Component {@Overridepublic void operation() {System.out.println("ConcreteComponent operation");}
}// 装饰器
abstract class Decorator implements Component {protected Component component;public void setComponent(Component component) {this.component = component;}@Overridepublic void operation() {if (component != null) {component.operation();}}
}// 具体装饰器 A
class ConcreteDecoratorA extends Decorator {@Overridepublic void operation() {super.operation();addedBehavior();}private void addedBehavior() {System.out.println("ConcreteDecoratorA added behavior");}
}// 具体装饰器 B
class ConcreteDecoratorB extends Decorator {@Overridepublic void operation() {super.operation();addedBehavior();}private void addedBehavior() {System.out.println("ConcreteDecoratorB added behavior");}
}// 客户端
public class Client {public static void main(String[] args) {Component component = new ConcreteComponent();ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();decoratorA.setComponent(component);decoratorB.setComponent(decoratorA);decoratorB.operation();// 输出:// ConcreteComponent operation// ConcreteDecoratorA added behavior// ConcreteDecoratorB added behavior}
}
C++ 代码案例
#include <iostream>// 组件接口
class Component {
public:virtual void operation() = 0;virtual ~Component() {}
};// 具体组件
class ConcreteComponent : public Component {
public:void operation() override {std::cout << "ConcreteComponent operation" << std::endl;}
};// 装饰器
class Decorator : public Component {
protected:Component* component;public:void setComponent(Component* component) {this->component = component;}void operation() override {if (component != nullptr) {component->operation();}}
};// 具体装饰器 A
class ConcreteDecoratorA : public Decorator {
public:void operation() override {Decorator::operation();addedBehavior();}void addedBehavior() {std::cout << "ConcreteDecoratorA added behavior" << std::endl;}
};// 具体装饰器 B
class ConcreteDecoratorB : public Decorator {
public:void operation() override {Decorator::operation();addedBehavior();}void addedBehavior() {std::cout << "ConcreteDecoratorB added behavior" << std::endl;}
};// 客户端
int main() {Component* component = new ConcreteComponent();Decorator* decoratorA = new ConcreteDecoratorA();Decorator* decoratorB = new ConcreteDecoratorB();decoratorA->setComponent(component);decoratorB->setComponent(decoratorA);decoratorB->operation();// 输出:// ConcreteComponent operation// ConcreteDecoratorA added behavior// ConcreteDecoratorB added behaviordelete component;delete decoratorA;delete decoratorB;return 0;
}
Python 代码案例
from abc import ABC, abstractmethod# 组件接口
class Component(ABC):@abstractmethoddef operation(self):pass# 具体组件
class ConcreteComponent(Component):def operation(self):print("ConcreteComponent operation")# 装饰器
class Decorator(Component):def __init__(self, component: Component):self._component = componentdef operation(self):if self._component:self._component.operation()# 具体装饰器 A
class ConcreteDecoratorA(Decorator):def operation(self):super().operation()self.added_behavior()def added_behavior(self):print("ConcreteDecoratorA added behavior")# 具体装饰器 B
class ConcreteDecoratorB(Decorator):def operation(self):super().operation()self.added_behavior()def added_behavior(self):print("ConcreteDecoratorB added behavior")# 客户端
if __name__ == "__main__":component = ConcreteComponent()decorator_a = ConcreteDecoratorA(component)decorator_b = ConcreteDecoratorB(decorator_a)decorator_b.operation()# 输出:# ConcreteComponent operation# ConcreteDecoratorA added behavior# ConcreteDecoratorB added behavior
Go 代码案例
package mainimport "fmt"// 组件接口
type Component interface {Operation()
}// 具体组件
type ConcreteComponent struct{}func (c *ConcreteComponent) Operation() {fmt.Println("ConcreteComponent operation")
}// 装饰器
type Decorator struct {component Component
}func (d *Decorator) SetComponent(component Component) {d.component = component
}func (d *Decorator) Operation() {if d.component != nil {d.component.Operation()}
}// 具体装饰器 A
type ConcreteDecoratorA struct {Decorator
}func (c *ConcreteDecoratorA) Operation() {c.Decorator.Operation()c.AddedBehavior()
}func (c *ConcreteDecoratorA) AddedBehavior() {fmt.Println("ConcreteDecoratorA added behavior")
}// 具体装饰器 B
type ConcreteDecoratorB struct {Decorator
}func (c *ConcreteDecoratorB) Operation() {c.Decorator.Operation()c.AddedBehavior()
}func (c *ConcreteDecoratorB) AddedBehavior() {fmt.Println("ConcreteDecoratorB added behavior")
}// 客户端
func main() {component := &ConcreteComponent{}decoratorA := &ConcreteDecoratorA{Decorator: Decorator{component: component}}decoratorB := &ConcreteDecoratorB{Decorator: Decorator{component: decoratorA}}decoratorB.Operation()// 输出:// ConcreteComponent operation// ConcreteDecoratorA added behavior// ConcreteDecoratorB added behavior
}

4. 总结

装饰模式 是一种结构型设计模式,它允许在不改变对象接口的前提下,动态地给对象增加额外的责任或功能。这种模式通过创建装饰类来包装原有类,并在保持类方法签名完整性的前提下,提供了额外的功能。

主要优点
  1. 灵活性:可以在运行时动态地添加或删除对象的责任,而不需要修改现有的代码。
  2. 可扩展性:可以很容易地通过组合不同的装饰器来实现复杂的功能。
  3. 符合开闭原则:可以在不修改现有代码的情况下,通过添加新的装饰器来扩展功能。
主要缺点
  1. 增加了系统的复杂性:装饰模式会引入许多小类,这可能会使系统的设计变得更复杂。
  2. 调试困难:由于装饰器可以层层嵌套,调试时可能难以跟踪到最终的行为。
适用场景
  • 当需要在运行时动态地给对象添加功能时。
  • 当需要扩展类的功能,但又不想使用继承的方式时。
  • 当系统需要提供多种可选功能,且这些功能可以自由组合时。

相关文章:

【设计模式】【结构型模式(Structural Patterns)】之装饰模式(Decorator Pattern)

1. 设计模式原理说明 装饰模式&#xff08;Decorator Pattern&#xff09; 是一种结构型设计模式&#xff0c;它允许在不改变对象接口的前提下&#xff0c;动态地给对象增加额外的责任或功能。这种模式创建了一个装饰类&#xff0c;用于包装原有的类&#xff0c;并在保持类方法…...

【AI】JetsonNano启动时报错:soctherm OC ALARM

1、问题描述 将JetsonNano烧写SD卡镜像为Ubuntu20.04后&#xff0c;启动时报错&#xff1a;soctherm OC ALARM&#xff0c;启动失败&#xff1b;然后系统一直重启 2、原因分析 “soctherm OC ALARM”是检测到系统温度超过安全阈值时发出的过热警告。 “soctherm”代表系统…...

QT:生成二维码 QRCode

目录 1.二维码历史2.QT源码3.界面展示4.工程源码链接 1.二维码历史 二维码&#xff08;2-Dimensional Bar Code&#xff09;&#xff0c;是用某种特定的几何图形按一定规律在平面&#xff08;二维方向上&#xff09;分布的黑白相间的图形记录数据符号信息的。它是指在一维条码…...

【LeetCode刷题之路】120:三角形最小路径和的两种解法(动态规划优化)

LeetCode刷题记录 &#x1f310; 我的博客主页&#xff1a;iiiiiankor&#x1f3af; 如果你觉得我的内容对你有帮助&#xff0c;不妨点个赞&#x1f44d;、留个评论✍&#xff0c;或者收藏⭐&#xff0c;让我们一起进步&#xff01;&#x1f4dd; 专栏系列&#xff1a;LeetCode…...

神经网络中常见的激活函数Sigmoid、Tanh和ReLU

激活函数在神经网络中起着至关重要的作用&#xff0c;它们决定了神经元的输出是否应该被激活以及如何非线性地转换输入信号。不同的激活函数适用于不同的场景&#xff0c;选择合适的激活函数可以显著影响模型的性能和训练效率。以下是三种常见的激活函数&#xff1a;Sigmoid、T…...

适用于学校、医院等低压用电场所的智能安全配电装置

引言 电力&#xff0c;作为一种清洁且高效的能源&#xff0c;极大地促进了现代生活的便捷与舒适。然而&#xff0c;与此同时&#xff0c;因使用不当或维护缺失等问题&#xff0c;漏电、触电事件以及电气火灾频发&#xff0c;对人们的生命安全和财产安全构成了严重威胁&#xf…...

基于python爬虫的智慧人才数据分析系统

废话不多说&#xff0c;先看效果图 更多效果图可私信我获取 源码分享 import os import sysdef main():"""Run administrative tasks."""os.environ.setdefault(DJANGO_SETTINGS_MODULE, 智慧人才数据分析系统.settings)try:from django.core.m…...

LeetCode-315. Count of Smaller Numbers After Self

目录 题目描述 解题思路 【C】 【Java】 复杂度分析 LeetCode-315. Count of Smaller Numbers After Selfhttps://leetcode.com/problems/count-of-smaller-numbers-after-self/description/ 题目描述 Given an integer array nums, return an integer array counts whe…...

根据导数的定义计算导函数

根据导数的定义计算导函数 1. Finding derivatives using the definition (使用定义求导)1.1. **We want to differentiate f ( x ) 1 / x f(x) 1/x f(x)1/x with respect to x x x**</font>1.2. **We want to differentiate f ( x ) x f(x) \sqrt{x} f(x)x ​ wi…...

WPF关于打开新窗口获取数据的回调方法的两种方式

一种基于消息发送模式 一种基于回调机制 基于消息发送模式 父页面定义接收的_selectedPnNumberStandarMsg保证是唯一 Messenger.Default.Register<PlateReplaceApplyModel>(this, _selectedPnNumberStandarMsgToken, platePnNumberModel > { …...

复杂网络(四)

一、规则网络 孤立节点网络全局耦合网络&#xff08;又称完全网络&#xff09;星型网络一维环二维晶格 编程实践&#xff1a; import networkx as nx import matplotlib.pyplot as pltn 10 #创建孤立节点图 G1 nx.Graph() G1.add_nodes_from(list(range(n))) plt.figure(f…...

用MATLAB符号工具建立机器人的动力学模型

目录 介绍代码功能演示拉格朗日方法回顾求解符号表达式数值求解 介绍 开发机器人过程中经常需要用牛顿-拉格朗日法建立机器人的动力学模型&#xff0c;表示为二阶微分方程组。本文以一个二杆系统为例&#xff0c;介绍如何用MATLAB符号工具得到微分方程表达式&#xff0c;只需要…...

SQL优化与性能——数据库设计优化

数据库设计优化是提高数据库性能、确保数据一致性和支持业务增长的关键环节。无论是大型企业应用还是小型项目&#xff0c;合理的数据库设计都能够显著提升系统性能、减少冗余数据、优化查询响应时间&#xff0c;并降低维护成本。本章将深入探讨数据库设计中的几个关键技术要点…...

FPGA存在的意义:为什么adc连续采样需要fpga来做,而不会直接用iic来实现

FPGA存在的意义&#xff1a;为什么adc连续采样需要fpga来做&#xff0c;而不会直接用iic来实现 原因ADS111x连续采样实现连续采样功能说明iic读取adc的数据速率 VS adc连续采样的速率adc连续采样的速率iic读取adc的数据速率结论分析 FPGA读取adc数据问题一&#xff1a;读取adc数…...

我们来学mysql -- 事务之概念(原理篇)

事务的概念 题记一个例子一致性隔离性原子性持久性 题记 在漫长的编程岁月中&#xff0c;存在一如既往地贯穿着工作&#xff0c;面试的概念这类知识点&#xff0c;事不关己当然高高挂起&#xff0c;精准踩坑时那心情也的却是日了&#x1f436;请原谅我的粗俗&#xff0c;遇到B…...

基于特征子空间的高维异常检测:一种高效且可解释的方法

本文将重点探讨一种替代传统单一检测器的方法&#xff1a;不是采用单一检测器分析数据集的所有特征&#xff0c;而是构建多个专注于特征子集(即子空间)的检测器系统。 在表格数据的异常检测实践中&#xff0c;我们的目标是识别数据中最为异常的记录&#xff0c;这种异常性可以…...

看不见的彼方:交换空间——小菜一碟

有个蓝色的链接&#xff0c;先去看看两年前的题目的write up &#xff08;https://github.com/USTC-Hackergame/hackergame2022-writeups/blob/master/official/%E7%9C%8B%E4%B8%8D%E8%A7%81%E7%9A%84%E5%BD%BC%E6%96%B9/README.md&#xff09; 从别人的write up中了解到&…...

YOLO模型训练后的best.pt和last.pt区别

在选择YOLO模型训练后的权重文件best.pt和last.pt时&#xff0c;主要取决于具体的应用场景‌&#xff1a;‌12 ‌best.pt‌&#xff1a;这个文件保存的是在训练过程中表现最好的模型权重。通常用于推理和部署阶段&#xff0c;因为它包含了在验证集上表现最好的模型权重&#x…...

Pareidoscope - 语言结构关联工具

文章目录 关于 Pareidoscope安装使用方法输入格式语料库查询 将语料库转换为 SQLite3 数据库两种语言结构之间的关联简单词素分析关联共现和伴随词素分析相关的更大结构可视化关联结构 关于 Pareidoscope Pareidoscope 是一组 用于确定任意语言结构之间 关联的工具&#xff0c…...

GPT(Generative Pre-trained Transformer) 和 Transformer的比较

GPT&#xff08;Generative Pre-trained Transformer&#xff09; 和 Transformer 的比较 flyfish 1. Transformer 是一种模型架构 Transformer 是一种通用的神经网络架构&#xff0c;由 Vaswani 等人在论文 “Attention Is All You Need”&#xff08;2017&#xff09;中提…...

三维GIS开发cesium智慧地铁教程(5)Cesium相机控制

一、环境搭建 <script src"../cesium1.99/Build/Cesium/Cesium.js"></script> <link rel"stylesheet" href"../cesium1.99/Build/Cesium/Widgets/widgets.css"> 关键配置点&#xff1a; 路径验证&#xff1a;确保相对路径.…...

关于iview组件中使用 table , 绑定序号分页后序号从1开始的解决方案

问题描述&#xff1a;iview使用table 中type: "index",分页之后 &#xff0c;索引还是从1开始&#xff0c;试过绑定后台返回数据的id, 这种方法可行&#xff0c;就是后台返回数据的每个页面id都不完全是按照从1开始的升序&#xff0c;因此百度了下&#xff0c;找到了…...

django filter 统计数量 按属性去重

在Django中&#xff0c;如果你想要根据某个属性对查询集进行去重并统计数量&#xff0c;你可以使用values()方法配合annotate()方法来实现。这里有两种常见的方法来完成这个需求&#xff1a; 方法1&#xff1a;使用annotate()和Count 假设你有一个模型Item&#xff0c;并且你想…...

最新SpringBoot+SpringCloud+Nacos微服务框架分享

文章目录 前言一、服务规划二、架构核心1.cloud的pom2.gateway的异常handler3.gateway的filter4、admin的pom5、admin的登录核心 三、code-helper分享总结 前言 最近有个活蛮赶的&#xff0c;根据Excel列的需求预估的工时直接打骨折&#xff0c;不要问我为什么&#xff0c;主要…...

Nuxt.js 中的路由配置详解

Nuxt.js 通过其内置的路由系统简化了应用的路由配置&#xff0c;使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...

高危文件识别的常用算法:原理、应用与企业场景

高危文件识别的常用算法&#xff1a;原理、应用与企业场景 高危文件识别旨在检测可能导致安全威胁的文件&#xff0c;如包含恶意代码、敏感数据或欺诈内容的文档&#xff0c;在企业协同办公环境中&#xff08;如Teams、Google Workspace&#xff09;尤为重要。结合大模型技术&…...

Neo4j 集群管理:原理、技术与最佳实践深度解析

Neo4j 的集群技术是其企业级高可用性、可扩展性和容错能力的核心。通过深入分析官方文档,本文将系统阐述其集群管理的核心原理、关键技术、实用技巧和行业最佳实践。 Neo4j 的 Causal Clustering 架构提供了一个强大而灵活的基石,用于构建高可用、可扩展且一致的图数据库服务…...

【Java_EE】Spring MVC

目录 Spring Web MVC ​编辑注解 RestController RequestMapping RequestParam RequestParam RequestBody PathVariable RequestPart 参数传递 注意事项 ​编辑参数重命名 RequestParam ​编辑​编辑传递集合 RequestParam 传递JSON数据 ​编辑RequestBody ​…...

【C语言练习】080. 使用C语言实现简单的数据库操作

080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...

汇编常见指令

汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX&#xff08;不访问内存&#xff09;XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...