咖啡馆根据配料不同收费java_Java 设计模式(3) —— 装饰者模式
时间: 2023-11-09 21:06:59 浏览: 43
装饰者模式是一种结构型设计模式,它允许你动态地向对象添加行为。通过将对象放入装饰器类中,可以在运行时更改对象的行为。
在咖啡馆中,装饰者模式可以用于根据顾客的选择动态地添加配料并计算价格。我们可以创建一个基础咖啡类,然后创建多个装饰器类来添加不同的配料,并且每个装饰器类都可以计算自己的价格。
下面是一个简单的示例代码:
```java
// 基础咖啡类
public abstract class Coffee {
protected String description = "Unknown coffee";
public String getDescription() {
return description;
}
public abstract double cost();
}
// 浓缩咖啡类
public class Espresso extends Coffee {
public Espresso() {
description = "Espresso";
}
public double cost() {
return 1.99;
}
}
// 装饰器类,用于添加牛奶
public class Milk extends Coffee {
private Coffee coffee;
public Milk(Coffee coffee) {
this.coffee = coffee;
}
public String getDescription() {
return coffee.getDescription() + ", Milk";
}
public double cost() {
return coffee.cost() + 0.5;
}
}
// 装饰器类,用于添加摩卡
public class Mocha extends Coffee {
private Coffee coffee;
public Mocha(Coffee coffee) {
this.coffee = coffee;
}
public String getDescription() {
return coffee.getDescription() + ", Mocha";
}
public double cost() {
return coffee.cost() + 0.8;
}
}
// 测试代码
public static void main(String[] args) {
Coffee coffee = new Espresso(); // 创建一个浓缩咖啡
coffee = new Milk(coffee); // 添加牛奶
coffee = new Mocha(coffee); // 添加摩卡
System.out.println(coffee.getDescription() + " $" + coffee.cost());
}
```
输出结果为:`Espresso, Milk, Mocha $3.29`
在这个例子中,我们创建了一个基础咖啡类 `Coffee`,并且创建了两个装饰器类 `Milk` 和 `Mocha`。我们可以通过创建不同的装饰器来添加不同的配料。最后,我们创建了一个浓缩咖啡对象 `Espresso`,并且动态地添加了牛奶和摩卡,最终计算出了价格。