题目如下:
代码如下:
package 真题;
public class test_2012_low {
public static void main(String[] args) {
Beverage beverage = new DarkRoast();
beverage = new Mocha(beverage);
beverage = new Mocha(beverage);
beverage = new Whip(beverage);
beverage = new Whip(beverage);
System.out.println(beverage.getDescription() + " ¥" + beverage.cost());
}
}
abstract class Beverage { //饮料的抽象类
String description = "Unknown Beverage";
String getDescription(){ //获取对饮料的描述
return description;
}
abstract int cost(); //抽象方法计算花费
}
abstract class CondimentDecorator extends Beverage { //配料的抽象类 继承饮料
Beverage beverage;
}
class Espresso extends Beverage { //蒸馏咖啡
private final int ESPRESSO_PRICE = 25; //定义蒸馏咖啡的价格
public Espresso() { //有参构造为描述赋值
description = "Espresso";
}
@Override
public int cost() { //返回价格
return ESPRESSO_PRICE;
}
}
class DarkRoast extends Beverage { //深度烘培咖啡
private final int DARKROAST_PRICE = 20; //定义深度烘焙咖啡价格
public DarkRoast() {
description = "DarkRoast";
}
@Override
public int cost() {
return DARKROAST_PRICE;
}
}
class Mocha extends CondimentDecorator { //定义加入摩卡配料
private final int MOCHA_PRICE = 10;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Mocha";
}
@Override
public int cost() {
return MOCHA_PRICE + beverage.cost();
} //摩卡继承配料类
}
class Whip extends CondimentDecorator { //定义加入奶泡配料
private final int WHIP_PRICE = 8;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Whip";
}
@Override
public int cost() {
return WHIP_PRICE + beverage.cost();
}
}
运行结果: