Java Reference
In-Depth Information
IMPLEMENTING THE DECORATOR PATTERN IN PLAIN CODE
If the classes are in the design stage, the addition of decorators shouldn't be too much of an issue.
However, if the decorator is to be implemented in an existing system, you might need to refactor some
classes. For example, the target class should implement the same interface that the decorator implements.
This chapter demonstrates the use of the decorator pattern using a simplii ed POS system for a pizza
restaurant. Each pizza can be “decorated” with extra toppings, such as double cheese and free chili.
First, you will create the Order interface, which is implemented by the Pizza class and by the
decorator's Extra abstract class. The Extra class is extended by the extra toppings classes:
DoubleExtra , NoCostExtra , and RegularExtra .
You'll start by creating the Order interface in Listing 7‐1.
LISTING: 7‐1: The Order interface
public interface Order {
public double getPrice();
public String getLabel();
}
In Listing 7‐2, you'll create the class that represents a pizza (Four Seasons, Margarita, Hawaiian,
and so on) on the menu. This is the target object to be decorated.
LISTING: 7‐2: The class to be decorated implements the Order interface
public class Pizza implements Order {
private String label;
private double price;
public Pizza(String label, double price){
this.label=label;
this.price=price;
}
public double getPrice(){
return this.price;
}
public String getLabel(){
return this.label;
}
}
The following code creates a Four Seasons pizza.
Order fourSeasonsPizza = new Pizza("Four Seasons Pizza", 10);
Next, you need to create the decorators that will decorate the pizza with extra toppings.
Use an abstract class so that the concrete classes do not have to implement all the business
 
Search WWH ::




Custom Search