本人新手,在java head first设计模式中装饰模式遇到个问题请教大家,问题就是设置饮料杯子的大小,根据杯子大小加上各自的价钱,写的代码如下,不知道为什么结果却不会根据设置的大小加上价钱?感觉应该SizeDecorator中的cost()方法有问题,但是又试不出来,求指点,谢谢
public abstract class Beverage {
String description="Unknown Beverage";
String size=null;
public String getDescription(){
return description;
}
public abstract double cost();
public void setSize(String size){
this.size=size;
}
public String getSize(){
return size;
}
}
public class SizeDecorator extends Beverage{
Beverage beverage;
String size=null;
public SizeDecorator(Beverage beverage){
this.beverage=beverage;
description=beverage.getDescription();
size=beverage.getSize();
}
public double cost(){
double x=beverage.cost();
if("tall".equals(size)){
x=+ .10;
}
else if("grande".equals(size)){
x=+ .15;
}
else if("venti".equals(size)){
x=+ .20;
}
return x;
}
}
public class StarbuzzCoffee {
public static void main(String[] args){
Beverage beverage=new Espresso();
System.out.println(beverage.getDescription()+"$"+beverage.cost());
Beverage beverage2=new DarkRoast();
beverage2=new Mocha(beverage2);
beverage2=new Mocha(beverage2);
beverage2=new Whip(beverage2);
beverage2=new SizeDecorator(beverage2);
beverage2.setSize("grande");
System.out.println(beverage2.getDescription()+"$"+beverage2.cost());
}
}
输出结果:
Espresso$1.99
Dark Roast,Mocha,Mocha,Whip$1.49