Jump to content


Photo

Why Do We Need The Condiment Decorator?


  • Please log in to reply
1 reply to this topic

#1 Richie Hamburg

Richie Hamburg

    New Member

  • Members
  • Pip
  • 2 posts

Posted 29 May 2014 - 08:22 AM

In the section "writing the StarBuzz code" it strikes me that there is no need for the CondimentDecorator class. Whats the issue with adding a Beverage reference to the base Beverage abstract class?When creating a condiment we simply super() back to the Beverage class to set the decoration reference. I expect this is mentioned or explained later in the book but if this way is simpler (I think it is) and still exhibits the features of decorators (it does) then maybe a note to explain why its not used?

public abstract class Beverage {
	Beverage beverage;
	private String description = "Unknown beverage";
	public Beverage(Beverage beverage) {
		this.beverage = beverage;
	}
        public Beverage() {
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getDescription() {
		return description;
	}
	public abstract Double cost();
}

The Espresso:

public class Espresso extends Beverage {
	public Espresso() {
		setDescription( "Espresso");
	}
	@Override
	public Double cost() {
		return 1.99;
	}
}

and now the Mocha and some test code:

public class Mocha extends Beverage {
	public Mocha(Beverage beverage) {
		super(beverage);
	}
	@Override
	public String getDescription() {
		return beverage.getDescription()+", "+"Mocha";
	}
	@Override
	public Double cost() {
		return .20 + beverage.cost();
	}
	public static void main(String[] args) {
		Beverage b = new Espresso();
		System.out.println(b.getDescription());
		b= new Mocha(<img src='http://forums.oreilly.com/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' />;
		b= new Mocha(<img src='http://forums.oreilly.com/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' />;
		b= new Mocha(<img src='http://forums.oreilly.com/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' />;
		System.out.println(b.getDescription());
		System.out.println( String.format("%.2f", b.cost()));
	}
}


#2 Richie Hamburg

Richie Hamburg

    New Member

  • Members
  • Pip
  • 2 posts

Posted 29 May 2014 - 11:40 AM

Somehow in the cut and paste the calls to create a new
Mocha
passing b changes to
Mocha(<img src='http://forums.oreilly.com/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' />
. Editing doesnt help.

Edited by Richie Hamburg, 29 May 2014 - 11:44 AM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users