This is a question on the behavior of the code rather then the pattern itself. I will lay out the code below
public abstract class Beverage {
protected String description;
public String getDescription(){
return description;
}
public abstract BigDecimal cost();
}
public abstract class CondimentDecorator extends Beverage{
@Override
public abstract String getDescription();
}
public class HouseBlend extends Beverage{
public HouseBlend() {
description = "House Blend";
}
@Override
public BigDecimal cost() {
return BigDecimal.valueOf(.89);
}
}
public class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
System.out.println("desc: " + beverage.getDescription());
return beverage.getDescription() + ", Mocha";
}
@Override
public BigDecimal cost() {
System.out.println("bev: "+beverage.cost());
return BigDecimal.valueOf(.20).add(beverage.cost());
}
}
public class CoffeeTest {
public static void main(String args[]){
Beverage blend = new HouseBlend();
blend = new Mocha(blend);
blend = new Mocha(blend);
blend = new Mocha(blend);
System.out.println(blend.getDescription() + " * "+blend.cost());
}
}
When CoffeeTest is run I get the following output which I would like to understand
1 desc: House Blend
2 desc: House Blend, Mocha
3 desc: House Blend
4 desc: House Blend, Mocha, Mocha
5 desc: House Blend
6 desc: House Blend, Mocha
7 desc: House Blend
8 bev: 0.89
9 bev: 1.09
10 bev: 0.89
11 bev: 1.29
12 bev: 0.89
13 bev: 1.09
14 bev: 0.89
15 House Blend, Mocha, Mocha, Mocha * 1.49
So these are my questions:
- I expected 'desc' and 'bev' to be printed 3x, so why the xtra lines?
- How is 'House Blend, Mocha, Mocha' printed when there is no explicit state saved?
- I have the same question about 'cost', how is
beverage.cost()
saving state by adding the amounts.
I am sure the answers lie in polymorphism between Beverage and CondimentDecorator.