请写出一个使用装饰器模式的代码示例,并说明该示例中每个类的职责和作用。
/**
* 装饰器模式是一种结构型设计模式,允许通过将对象放入包含行为的特殊封装对象中来动态地扩展对象的功能。
* 以下是一个使用装饰器模式的代码示例,模拟了咖啡店的订单系统。
*/
// 1. 定义一个抽象组件接口
interface Coffee {
double getCost();
String getDescription();
}
// 2. 实现具体的组件类
class SimpleCoffee implements Coffee {
@Override
public double getCost() {
return 1.0; // 基础咖啡的价格
}
@Override
public String getDescription() {
return "Simple Coffee"; // 基础咖啡的描述
}
}
// 3. 定义装饰器抽象类
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
@Override
public double getCost() {
return decoratedCoffee.getCost();
}
@Override
public String getDescription() {
return decoratedCoffee.getDescription();
}
}
// 4. 实现具体的装饰器类
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
@Override
public double getCost() {
return super.getCost() + 0.5; // 加牛奶的价格
}
@Override
public String getDescription() {
return super.getDescription() + ", Milk"; // 加牛奶的描述
}
}
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
@Override
public double getCost() {
return super.getCost() + 0.2; // 加糖的价格
}
@Override
public String getDescription() {
return super.getDescription() + ", Sugar"; // 加糖的描述
}
}
// 5. 客户端代码
public class DecoratorPatternExample {
public static void main(String[] args) {
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("Cost: " + simpleCoffee.getCost() + "; Description: " + simpleCoffee.getDescription());
Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println("Cost: " + milkCoffee.getCost() + "; Description: " + milkCoffee.getDescription());
Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
System.out.println("Cost: " + sugarMilkCoffee.getCost() + "; Description: " + sugarMilkCoffee.getDescription());
}
}
代码中各类的职责和作用:
-
Coffee 接口:
- 定义了所有具体组件和装饰器的共同接口,包含
getCost()和getDescription()方法。 - 作用:确保所有具体组件和装饰器遵循统一的规范。
- 定义了所有具体组件和装饰器的共同接口,包含
-
SimpleCoffee 类:
- 具体组件类,实现了
Coffee接口,代表基础咖啡。 - 作用:提供最基础的咖啡功能,初始化咖啡的价格和描述。
- 具体组件类,实现了
-
CoffeeDecorator 抽象类:
- 装饰器抽象类,实现了
Coffee接口,并持有一个Coffee对象的引用。 - 作用:作为所有装饰器的父类,定义了装饰器的基本行为(委托给被装饰对象)。
- 装饰器抽象类,实现了
-
MilkDecorator 和 SugarDecorator 类:
- 具体装饰器类,继承自
CoffeeDecorator,分别用于添加牛奶和糖的功能。 - 作用:动态扩展
Coffee对象的功能,例如增加价格和修改描述。
- 具体装饰器类,继承自
-
Client 类(DecoratorPatternExample):
- 客户端代码,通过组合具体组件和装饰器来完成功能扩展。
- 作用:演示如何使用装饰器模式动态地为对象添加功能。
总结: 装饰器模式的核心在于通过组合而非继承来扩展功能,使得功能扩展更加灵活。在此示例中,我们可以动态地为咖啡添加牛奶或糖,而无需修改原有代码。这种模式特别适合需要动态扩展功能的场景。