Note that there are some explanatory texts on larger screens.

plurals
  1. POHead First Design Patterns: Decorator behavior puzzling
    text
    copied!<p>This is a question on the behavior of the code rather then the pattern itself. I will lay out the code below</p> <pre><code> 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()); } } </code></pre> <p>When CoffeeTest is run I get the following output which I would like to understand</p> <pre><code>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 </code></pre> <p>So these are my questions:</p> <ol> <li>I expected 'desc' and 'bev' to be printed 3x, so why the xtra lines? </li> <li>How is 'House Blend, Mocha, Mocha' printed when there is no explicit state saved?</li> <li>I have the same question about 'cost', how is <code>beverage.cost()</code> saving state by adding the amounts.</li> </ol> <p>I am sure the answers lie in polymorphism between Beverage and CondimentDecorator.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload