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

23种设计模式-结构型模式之装饰器模式(Java版本)

Java 装饰器模式(Decorator Pattern)详解

🎁 什么是装饰器模式?

装饰器模式是一种结构型设计模式,允许向一个对象动态添加新的功能,而不改变其结构。

🧱 你可以想象成在原有功能上“包裹”一层新功能,就像“套娃”或者“包礼物”。


🧠 使用场景

  • 需要在不修改类的情况下,扩展其功能
  • 需要动态地为对象添加功能
  • 多个类只有少量差异时,使用继承会导致类爆炸

🏗️ 模式结构

  • Component(抽象构件):定义对象接口
  • ConcreteComponent(具体构件):被装饰的原始对象
  • Decorator(装饰器抽象类):持有组件对象的引用,扩展功能
  • ConcreteDecorator(具体装饰器):实现具体增强功能

✅ 示例:咖啡加配料

抽象组件

public interface Coffee {String getDescription();double cost();
}

具体组件

public class SimpleCoffee implements Coffee {@Overridepublic String getDescription() {return "普通咖啡";}@Overridepublic double cost() {return 5.0;}
}

抽象装饰器

public abstract class CoffeeDecorator implements Coffee {protected Coffee decoratedCoffee;public CoffeeDecorator(Coffee coffee) {this.decoratedCoffee = coffee;}@Overridepublic String getDescription() {return decoratedCoffee.getDescription();}@Overridepublic double cost() {return decoratedCoffee.cost();}
}

具体装饰器:加牛奶

public class MilkDecorator extends CoffeeDecorator {public MilkDecorator(Coffee coffee) {super(coffee);}@Overridepublic String getDescription() {return super.getDescription() + " + 牛奶";}@Overridepublic double cost() {return super.cost() + 2.0;}
}

具体装饰器:加糖

public class SugarDecorator extends CoffeeDecorator {public SugarDecorator(Coffee coffee) {super(coffee);}@Overridepublic String getDescription() {return super.getDescription() + " + 糖";}@Overridepublic double cost() {return super.cost() + 1.0;}
}

客户端使用

public class Main {public static void main(String[] args) {Coffee coffee = new SimpleCoffee();coffee = new MilkDecorator(coffee);coffee = new SugarDecorator(coffee);System.out.println(coffee.getDescription() + ",价格:" + coffee.cost());}
}

🧩 优点

  • 灵活、可扩展性强,支持动态组合
  • 避免类继承造成的类爆炸
  • 满足开闭原则

⚠️ 缺点

  • 多层装饰器会增加系统复杂度,调试不易
  • 对象结构可能过于复杂,难以理解

✅ 使用建议

  • 当你希望在运行时增加对象行为,而不是通过继承
  • 多个类之间功能相似,可通过组合代替继承

相关文章:

  • 延长(暂停)Windows更新
  • 学习设计模式《四》——单例模式
  • Halcon应用:相机标定
  • Deepseek输出的内容如何直接转化为word文件?
  • 大模型面经 | 介绍一下CLIP和BLIP
  • QSS【QT】
  • React 文章 分页
  • TDengine 性能监控与调优实战指南(一)
  • Docker Compose 外部网络(`external: true`)与内部网络的区别
  • 5、openfeign
  • 对于在线教育或知识付费类网站视频处理方案
  • 学习笔记:黑马程序员JavaWeb开发教程(2025.3.24)
  • 海拔与大气压关系,大气压单位,气压传感器对比
  • DeepSeek与ECharts融合助力复杂图表高效制作
  • 声音识别(声纹识别)和语音识别的区别
  • python爬虫复习
  • SpringBoot 知识图谱
  • 小迪第10天http/s数据包
  • uni-app中map的使用
  • idea中导入从GitHub上克隆下来的springboot项目解决找不到主类的问题
  • 阿塞拜疆总统阿利耶夫将访华
  • 俄“联盟MS-26”载人飞船安全返回地球
  • 累计亏损10亿元,桂林旅游怎么了?
  • 五一出境游火爆:境外包车订单增长25%,日本酒店价格贵了好几倍
  • 加快从数量增长向品质跃升转变,促进生态空间与城市功能有机共生!龚正调研公园城市建设工作
  • 华夏幸福:累计未能如期偿还债务金额合计为227.91亿元