Java Reference
In-Depth Information
Next, you need to create the NoCostDecorator , which modii es the
label string but does not add to
the cost of the pizza. See Listing 7‐5.
LISTING 7‐5: The decorator that adds extra toppings at no cost
public class NoCostExtra extends Extra {
public NoCostExtra(String label, double price, Order order) {
super(label, price, order);
}
public Double getPrice() {
return order.getPrice();
}
}
Finally, in Listing 7‐6, you implement the DoubleExtra decorator to avoid printing the topping
twice on the label. The decorator doubles the price and adds the keyword double in front of the
target label.
LISTING 7‐6: The decorator that adds double toppings
public class DoubleExtra extends Extra {
public DoubleExtra(String label, double price, Order order) {
super(label, price, order);
}
public Double getPrice() {
return (this.price*2)+order.getPrice();
}
public String getLabel() {
return order.getLabel()+ ", Double " + this.label;
}
}
Now that the decorator pattern has been implemented to add extra toppings to your pizza, you can
test your implementation.
Order fourSeasonsPizza = new Pizza("Four Seasons Pizza", 10);
fourSeasonsPizza = new RegularExtra("Pepperoni", 4, fourSeasonsPizza );
fourSeasonsPizza = new DoubleExtra("Mozzarella", 2, fourSeasonsPizza );
fourSeasonsPizza = new NoCostExtra("Chili", 2, fourSeasonsPizza );
System.out.println(fourSeasonsPizza.getPrice());
System.out.println(fourSeasonsPizza.getLabel());
The output in the console will be as follows:
18.0
Pizza, Pepperoni, Double Mozzarella, Chili
Search WWH ::




Custom Search