设计模式: 装饰器

装饰者模式:

在不改变原有对象的基础上,动态的将功能附加到对象上,提供了比继承更有弹性的替代方案,也体现了开闭原则

注意事项

装饰者模式 VS 继承

目的都是为了要扩展对象的功能,装饰者模式可以提供比继承更多的灵活性

使用装饰着模式,相对于继承而言,需要的类的数目大大减少,再另一方面也会比继承产生更多的对象

使用场景

需要给一个现有类添加职责,但是又不能采用生成子类的方式去扩展的时候

当需要对于现有的一组基本功能进行组合,会产生非常多的功能的时候

当对象的功能要求可以同台的添加,或者说动态的撤销的时候

原理类图

角色分析

  • Component: 抽象主体、定义了一个主体的模板
  • ConcreteComponentA, B: 具体的主体,里面定义具体的业务逻辑
  • Decorator: 装饰者
  • ConcreteDecoratorA, B: 封装具体的装饰细节的实现类
java 复制代码
/**  
* @desc 抽象主体  
*/  
@Data  
public abstract class Coffee {  
  
private String desc;  
  
private float price;  
  
public abstract float cost();  
}  
  
/**  
* @desc 业务实体  
*/  
public class Cappuccino extends Coffee {  
  
public Cappuccino(){  
setPrice(12.2f);  
setDesc("卡布奇诺");  
}  
  
@Override  
public float cost(){  
System.out.println("当前价格为: " + getPrice());  
return getPrice();  
}  
}  
java 复制代码
  
/**  
* @desc 装饰器  
*/  
public class Decorator extends Coffee{  
  
private Coffee coffee;  
  
public Decorator(Coffee coffee){  
this.coffee = coffee;  
}  
  
// 重新计算方法: 递归实现  
@Override  
public float cost() {  
return super.getPrice() + coffee.cost();  
}  
  
@Override  
public String getDesc(){  
return super.getDesc() + coffee.getDesc();  
}  
}  
/**  
* @desc 装饰细节: 牛奶  
*/  
public class Milk extends Decorator {  
public Milk(Coffee coffee) {  
super(coffee);  
  
setDesc("加了一份牛奶,");  
  
setPrice(2.3f);  
}  
}  
  
/**  
* @desc 装饰器: 糖  
*/  
public class Sugar extends Decorator{  
public Sugar(Coffee coffee) {  
super(coffee);  
  
setDesc("加了份糖,");  
  
setPrice(1.5f);  
}  
}  
java 复制代码
/**  
* @desc 消费者  
*/  
public class CoffeeStore {  
  
  
public static void main(String... args){  
// 卡布奇诺, 1份牛奶,2份糖  
Coffee order = new Cappuccino();  
System.out.println("当前描述: " + order.getDesc() + " 当前价格: " + order.cost());  
  
order = new Milk(order);  
System.out.println("当前描述: " + order.getDesc() + " 当前价格: " + order.cost());  
  
order = new Sugar(order);  
order = new Sugar(order);  
System.out.println("当前描述: " + order.getDesc() + " 当前价格: " + order.cost());  
}  
}  
相关推荐
Lhappy嘻嘻1 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
herosunly1 小时前
60ms 不是启动快,而是不用重新启动:CubeSandbox 极速冷启动架构拆解
架构·cube sandbox
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
zlinear数据采集卡3 小时前
从气动比例阀到任意波形:硬核拆解ZLinear采集卡的DAC输出架构与工业闭环控制实战
arm开发·架构
懒鸟一枚4 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
2601_961946084 小时前
AI API 网关实战:从单 Key 管理到企业级多租户架构
大数据·人工智能·金融·架构·api·个人开发
我命由我123456 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑6 小时前
Sentinel安装
java·后端·微服务
XUHUOJUN6 小时前
Windows 2025架构深度分析之Stretch Cluster 延迟工程现实
windows·microsoft·架构·azure local
Web极客码7 小时前
突破并发瓶颈:云端高性能架构如何赋能海外 AI Agent 矩阵的高效产出
服务器·人工智能·架构