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());}
}
🧩 优点
- 灵活、可扩展性强,支持动态组合
- 避免类继承造成的类爆炸
- 满足开闭原则
⚠️ 缺点
- 多层装饰器会增加系统复杂度,调试不易
- 对象结构可能过于复杂,难以理解
✅ 使用建议
- 当你希望在运行时增加对象行为,而不是通过继承
- 多个类之间功能相似,可通过组合代替继承