O'Reilly Forums: Why Do We Need The Condiment Decorator? - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Why Do We Need The Condiment Decorator?

#1 User is offline   Richie Hamburg 

  • New Member
  • Pip
  • Group: Members
  • Posts: 2
  • Joined: 29-May 14

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(B);
		b= new Mocha(B);
		b= new Mocha(B);
		System.out.println(b.getDescription());
		System.out.println( String.format("%.2f", b.cost()));
	}
}

0

#2 User is offline   Richie Hamburg 

  • New Member
  • Pip
  • Group: Members
  • Posts: 2
  • Joined: 29-May 14

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(B)
. Editing doesnt help.

This post has been edited by Richie Hamburg: 29 May 2014 - 11:44 AM

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users