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

设计模式之装饰者模式

目录

  • 定义
  • 结构
  • 适用场景
  • 使用示例

定义

       装饰者模式是一种‌结构型设计模式‌,它通过将对象放入包含行为的特殊封装对象中,从而‌动态地为原对象添加新功能‌。

结构

在这里插入图片描述

适用场景

1)‌动态扩展功能‌
       需要在运行时为对象灵活添加或撤销功能,且这些功能可自由组合。
‌        例如:为咖啡动态添加牛奶、糖、摩卡等配料。
2)‌避免继承爆炸‌
       当子类数量过多(如 MilkCoffee、SugarCoffee、MilkSugarCoffee…)时,装饰者模式提供更优雅的扩展方案。
3)‌不可修改原对象代码‌
       当无法修改原对象代码(如第三方库的类),但需扩展其行为时。
4)‌多层次功能叠加‌
       功能需要按不同顺序组合(如先加糖再加牛奶 vs 先加牛奶再加糖)。

使用示例

以下是装饰者模式在IO中的简化示例。
定义抽象组件

import java.io.IOException;/*** 抽象组件*/
public interface InputStream {int read() throws IOException;void close() throws IOException;}

定义具体组件

import java.io.IOException;public class FileInputStream implements InputStream {private String filename;public FileInputStream(String filename) {this.filename = filename;}@Overridepublic int read() throws IOException {System.out.println("从文件" + filename + "读取字节");return 0; // 模拟返回字节}@Overridepublic void close() throws IOException {System.out.println("关闭文件" + filename);}
}

定义抽象装饰者

import java.io.IOException;/*** 抽象装饰者*/
public abstract class FilterInputStream implements InputStream {protected InputStream wrappee;public FilterInputStream(InputStream in) {this.wrappee = in;}@Overridepublic abstract int read() throws IOException;@Overridepublic void close() throws IOException {wrappee.close();}
}

定义具体装饰者

import java.io.IOException;/*** 具体装饰者A*/
public class BufferedInputStream extends FilterInputStream {public BufferedInputStream(InputStream in) {super(in);}@Overridepublic int read() throws IOException {System.out.println("从缓冲区读取字节");return wrappee.read();}
}
import java.io.IOException;/*** 具体装饰者B*/
public class DataInputStream extends FilterInputStream {public DataInputStream(InputStream in) {super(in);}@Overridepublic int read() throws IOException {System.out.println("读取并转换数据类型");return wrappee.read();}public String readUTF() throws IOException {return "装饰后的字符串数据";}
}

测试

import java.io.IOException;public class Client {public static void main(String[] args) throws IOException {InputStream in = new FileInputStream("test.txt");in = new BufferedInputStream(in);in = new DataInputStream(in);in.read();System.out.println(((DataInputStream) in).readUTF());in.close();}}

相关文章:

  • Wpf布局之UniformGrid面板!
  • day44-Django RestFramework(drf)下
  • 大数据Hadoop之——安装部署hadoop
  • INA226 电流计 功率计电路图转PCB制作
  • WPF学习笔记(12)下拉框控件ComboBox与数据模板
  • 矩阵的定义和运算 线性代数
  • NoSQL与Redis、HBase、分布式系统详解
  • 青少年编程与数学 02-022 专业应用软件简介 01 设计与创意类软件:Adobe Creative Cloud
  • 解锁云原生微服务架构:搭建与部署实战全攻略
  • 6-创建和查询
  • 接口自动化测试(Python+pytest+PyMySQL+Jenkins)
  • AlpineLinux安装部署elasticsearch
  • 如何搭建基于RK3588的边缘服务器集群?支持12个RK3588云手机
  • solidworks2021导出urdf
  • [Android]ANR的线程
  • 理解WebGL中的顶点着色器和片元着色器
  • git lfs 提交大文件
  • 解决git clone报错:fatal unable to access xxx. Could not resolve host github.com
  • 【PaddleOCR】PaddlePaddle 3.0环境安装,及PaddleOCR3.0 快速入门使用
  • MCP -1(待补充)