Java Reference
In-Depth Information
But wait! There is a potential bug! Chili is not free if you order it as a side dish, but the chef is happy to
offer it free on a pizza. You need to make sure the system accounts for those differences. Just imagine
that these values and labels come from a database. What would you do to create different behaviors
for chili? One option might be to create two chili objects: one labeled as “with pizza.” Clearly, this
would be a hack, leaving a backdoor open for any waiter to order free chili for his friends. Another
option would be to create an additional constructor method in the abstract class that does not take a
price parameter. Any decorator that does not charge for extras could implement this.
Unlike most other patterns described in this topic, you implement the decorator pattern by
declaring the decorator classes in the bean.xml deployment descriptor (except when annotated
with @Priority ; see the following section“Decorators Without XML Coni guration”). Luckily, this
coni guration is simple and gives you the advantage of pluggability and control over the order in
which the decorators are invoked.
The decorator implementation in Java EE introduces two new annotations: @Decorator and
@Delegate . @Decorator annotates the decorator class, and @Delegate annotates the delegate
injection point where the class to be decorated is injected.
You will use the example of a shop that wants to discount some of its products. It will use a
decorator to apply this discount to the regular retail price. In Listing 7‐7, you start by creating the
interface that you will use to connect the decorator with the object you want to decorate.
LISTING 7‐7: The Product interface
public interface Product {
public void setLabel(String label);
public void setPrice(double price);
public String getLabel();
public double getPrice();
public String generateLabel();
The interface introduces the generateLabel method, which the decorator implements to add its
discounting behavior. In Listing 7‐8, you create the Table class. It is the product that you want to be
decorated; therefore, it implements the Product interface.
LISTING 7‐8: The class to be decorated implements the Product interface
public class Table implements Product {
private String label = "Dining Table";
private double price = 100.00;
public void setLabel(String label) {
this.label = label;
Search WWH ::

Custom Search