【设计模式】【结构型模式(Structural Patterns)】之装饰模式(Decorator Pattern)
1. 设计模式原理说明
装饰模式(Decorator Pattern) 是一种结构型设计模式,它允许在不改变对象接口的前提下,动态地给对象增加额外的责任或功能。这种模式创建了一个装饰类,用于包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
主要角色
- Component(组件):定义了一个对象接口,可以给这些对象动态地添加职责。
- ConcreteComponent(具体组件):定义了一个具体的对象,也可以给这个对象添加一些责任。
- Decorator(装饰器):持有一个
Component对象的实例,并定义了一个与Component接口一致的接口。 - 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. 总结
装饰模式 是一种结构型设计模式,它允许在不改变对象接口的前提下,动态地给对象增加额外的责任或功能。这种模式通过创建装饰类来包装原有类,并在保持类方法签名完整性的前提下,提供了额外的功能。
主要优点
- 灵活性:可以在运行时动态地添加或删除对象的责任,而不需要修改现有的代码。
- 可扩展性:可以很容易地通过组合不同的装饰器来实现复杂的功能。
- 符合开闭原则:可以在不修改现有代码的情况下,通过添加新的装饰器来扩展功能。
主要缺点
- 增加了系统的复杂性:装饰模式会引入许多小类,这可能会使系统的设计变得更复杂。
- 调试困难:由于装饰器可以层层嵌套,调试时可能难以跟踪到最终的行为。
适用场景
- 当需要在运行时动态地给对象添加功能时。
- 当需要扩展类的功能,但又不想使用继承的方式时。
- 当系统需要提供多种可选功能,且这些功能可以自由组合时。
相关文章:
【设计模式】【结构型模式(Structural Patterns)】之装饰模式(Decorator Pattern)
1. 设计模式原理说明 装饰模式(Decorator Pattern) 是一种结构型设计模式,它允许在不改变对象接口的前提下,动态地给对象增加额外的责任或功能。这种模式创建了一个装饰类,用于包装原有的类,并在保持类方法…...
【AI】JetsonNano启动时报错:soctherm OC ALARM
1、问题描述 将JetsonNano烧写SD卡镜像为Ubuntu20.04后,启动时报错:soctherm OC ALARM,启动失败;然后系统一直重启 2、原因分析 “soctherm OC ALARM”是检测到系统温度超过安全阈值时发出的过热警告。 “soctherm”代表系统…...
QT:生成二维码 QRCode
目录 1.二维码历史2.QT源码3.界面展示4.工程源码链接 1.二维码历史 二维码(2-Dimensional Bar Code),是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的。它是指在一维条码…...
【LeetCode刷题之路】120:三角形最小路径和的两种解法(动态规划优化)
LeetCode刷题记录 🌐 我的博客主页:iiiiiankor🎯 如果你觉得我的内容对你有帮助,不妨点个赞👍、留个评论✍,或者收藏⭐,让我们一起进步!📝 专栏系列:LeetCode…...
神经网络中常见的激活函数Sigmoid、Tanh和ReLU
激活函数在神经网络中起着至关重要的作用,它们决定了神经元的输出是否应该被激活以及如何非线性地转换输入信号。不同的激活函数适用于不同的场景,选择合适的激活函数可以显著影响模型的性能和训练效率。以下是三种常见的激活函数:Sigmoid、T…...
适用于学校、医院等低压用电场所的智能安全配电装置
引言 电力,作为一种清洁且高效的能源,极大地促进了现代生活的便捷与舒适。然而,与此同时,因使用不当或维护缺失等问题,漏电、触电事件以及电气火灾频发,对人们的生命安全和财产安全构成了严重威胁…...
基于python爬虫的智慧人才数据分析系统
废话不多说,先看效果图 更多效果图可私信我获取 源码分享 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 > { …...
复杂网络(四)
一、规则网络 孤立节点网络全局耦合网络(又称完全网络)星型网络一维环二维晶格 编程实践: import networkx as nx import matplotlib.pyplot as pltn 10 #创建孤立节点图 G1 nx.Graph() G1.add_nodes_from(list(range(n))) plt.figure(f…...
用MATLAB符号工具建立机器人的动力学模型
目录 介绍代码功能演示拉格朗日方法回顾求解符号表达式数值求解 介绍 开发机器人过程中经常需要用牛顿-拉格朗日法建立机器人的动力学模型,表示为二阶微分方程组。本文以一个二杆系统为例,介绍如何用MATLAB符号工具得到微分方程表达式,只需要…...
SQL优化与性能——数据库设计优化
数据库设计优化是提高数据库性能、确保数据一致性和支持业务增长的关键环节。无论是大型企业应用还是小型项目,合理的数据库设计都能够显著提升系统性能、减少冗余数据、优化查询响应时间,并降低维护成本。本章将深入探讨数据库设计中的几个关键技术要点…...
FPGA存在的意义:为什么adc连续采样需要fpga来做,而不会直接用iic来实现
FPGA存在的意义:为什么adc连续采样需要fpga来做,而不会直接用iic来实现 原因ADS111x连续采样实现连续采样功能说明iic读取adc的数据速率 VS adc连续采样的速率adc连续采样的速率iic读取adc的数据速率结论分析 FPGA读取adc数据问题一:读取adc数…...
我们来学mysql -- 事务之概念(原理篇)
事务的概念 题记一个例子一致性隔离性原子性持久性 题记 在漫长的编程岁月中,存在一如既往地贯穿着工作,面试的概念这类知识点,事不关己当然高高挂起,精准踩坑时那心情也的却是日了🐶请原谅我的粗俗,遇到B…...
基于特征子空间的高维异常检测:一种高效且可解释的方法
本文将重点探讨一种替代传统单一检测器的方法:不是采用单一检测器分析数据集的所有特征,而是构建多个专注于特征子集(即子空间)的检测器系统。 在表格数据的异常检测实践中,我们的目标是识别数据中最为异常的记录,这种异常性可以…...
看不见的彼方:交换空间——小菜一碟
有个蓝色的链接,先去看看两年前的题目的write up (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) 从别人的write up中了解到&…...
YOLO模型训练后的best.pt和last.pt区别
在选择YOLO模型训练后的权重文件best.pt和last.pt时,主要取决于具体的应用场景:12 best.pt:这个文件保存的是在训练过程中表现最好的模型权重。通常用于推理和部署阶段,因为它包含了在验证集上表现最好的模型权重&#x…...
Pareidoscope - 语言结构关联工具
文章目录 关于 Pareidoscope安装使用方法输入格式语料库查询 将语料库转换为 SQLite3 数据库两种语言结构之间的关联简单词素分析关联共现和伴随词素分析相关的更大结构可视化关联结构 关于 Pareidoscope Pareidoscope 是一组 用于确定任意语言结构之间 关联的工具,…...
GPT(Generative Pre-trained Transformer) 和 Transformer的比较
GPT(Generative Pre-trained Transformer) 和 Transformer 的比较 flyfish 1. Transformer 是一种模型架构 Transformer 是一种通用的神经网络架构,由 Vaswani 等人在论文 “Attention Is All You Need”(2017)中提…...
linux之kylin系统nginx的安装
一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源(HTML/CSS/图片等),响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址,提高安全性 3.负载均衡服务器 支持多种策略分发流量…...
Leetcode 3576. Transform Array to All Equal Elements
Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接:3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到…...
阿里云ACP云计算备考笔记 (5)——弹性伸缩
目录 第一章 概述 第二章 弹性伸缩简介 1、弹性伸缩 2、垂直伸缩 3、优势 4、应用场景 ① 无规律的业务量波动 ② 有规律的业务量波动 ③ 无明显业务量波动 ④ 混合型业务 ⑤ 消息通知 ⑥ 生命周期挂钩 ⑦ 自定义方式 ⑧ 滚的升级 5、使用限制 第三章 主要定义 …...
Qt Widget类解析与代码注释
#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this); }Widget::~Widget() {delete ui; }//解释这串代码,写上注释 当然可以!这段代码是 Qt …...
Vue2 第一节_Vue2上手_插值表达式{{}}_访问数据和修改数据_Vue开发者工具
文章目录 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染2. 插值表达式{{}}3. 访问数据和修改数据4. vue响应式5. Vue开发者工具--方便调试 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染 准备容器引包创建Vue实例 new Vue()指定配置项 ->渲染数据 准备一个容器,例如: …...
macOS多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用
文章目录 问题现象问题原因解决办法 问题现象 macOS启动台(Launchpad)多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用。 问题原因 很明显,都是Google家的办公全家桶。这些应用并不是通过独立安装的…...
页面渲染流程与性能优化
页面渲染流程与性能优化详解(完整版) 一、现代浏览器渲染流程(详细说明) 1. 构建DOM树 浏览器接收到HTML文档后,会逐步解析并构建DOM(Document Object Model)树。具体过程如下: (…...
高等数学(下)题型笔记(八)空间解析几何与向量代数
目录 0 前言 1 向量的点乘 1.1 基本公式 1.2 例题 2 向量的叉乘 2.1 基础知识 2.2 例题 3 空间平面方程 3.1 基础知识 3.2 例题 4 空间直线方程 4.1 基础知识 4.2 例题 5 旋转曲面及其方程 5.1 基础知识 5.2 例题 6 空间曲面的法线与切平面 6.1 基础知识 6.2…...
spring:实例工厂方法获取bean
spring处理使用静态工厂方法获取bean实例,也可以通过实例工厂方法获取bean实例。 实例工厂方法步骤如下: 定义实例工厂类(Java代码),定义实例工厂(xml),定义调用实例工厂ÿ…...
如何在最短时间内提升打ctf(web)的水平?
刚刚刷完2遍 bugku 的 web 题,前来答题。 每个人对刷题理解是不同,有的人是看了writeup就等于刷了,有的人是收藏了writeup就等于刷了,有的人是跟着writeup做了一遍就等于刷了,还有的人是独立思考做了一遍就等于刷了。…...
