Java Reference
In-Depth Information
methods of an interface. An abstract decorator will create a blueprint that other decorators can
Perhaps you have different topping types (cheese, chili, pineapple, and so on). Imagine that the
customer wants to order the meal a little spicier, and the restaurant will not charge for that extra
topping. So you need a decorator that does not add to the price of the pizza but provides proper
labeling (that extra chili has been requested). Also, the customer may ask for two extra portions
of cheese, and if the system prints “cheese” twice, the chef may think it is a bug and add only one
portion of cheese. So you need another concrete decorator to allow for proper labeling of double
toppings. Listing 7‐3 accomplishes your goals.
LISTING 7‐3: The abstract decorator that adds extra toppings
public abstract class Extra implements Order {
protected Order order;
protected String label;
protected double price;
public Extra(String label, double price, Order order) {
// Price can be a big issue, so delegate this to concrete implementation
public abstract double getPrice();
// Should be okay to provide standard labeling
public String getLabel() {
return order.getLabel()+", "+this.label;
Now that you have the abstract decorator, you can add specii c behaviors and create concrete
decorators. You'll start with the RegularExtra decorator, which adds a charge and a label to the
target object (the pizza). Because the labeling function is already provided by the abstract decorator
and inherited by all subclasses that extend it, you only need to implement the pricing functionality.
Listing 7‐4 takes care of that.
LISTING 7‐4: The decorator that adds extra toppings
public class RegularExtra extends Extra {
public RegularExtra(String label, double price, Order order) {
super(label, price, order);
public Double getPrice() {
return this.price+order.getPrice();
Search WWH ::

Custom Search