This is a question about the behavior of the code, not the template 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 running, 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 3 times, so why xtra lines?
- How is "House Blend, Mocha, Mocha" printed in the absence of an explicit state?
- I have the same question about the "cost" of how
beverage.cost()to maintain a fortune by adding amounts.
I am sure that the answers lie in the polymorphism between Beverage and CondimentDecorator.
source
share