Java Reference
In-Depth Information
LISTING 7-8
(continued)
}
public void setPrice(double price) {
this.price = price;
}
public String getLabel() {
return label;
}
public double getPrice() {
return price;
}
public String generateLabel() {
return price + ", " + label;
}
}
You create the
PriceDiscountDecorator
decorator by implementing the
Product
interface. This class
implements the
generateLabel
method and adds its discounting behavior. The decorator reduces the
price of a product by 50 percent and adds the text “(Discounted)” to the product's label.
To enable the container to identify this class as a decorator, you must annotate it with
@Decorator
.
r
The delegate injection point (the instance that will be decorated) is annotated with
@Delegate
and
must be an injected i eld, an initializer method parameter, or a bean constructor method parameter.
The delegate type must be the interface implemented by the classes that you want to be decorated—
in this case,
Product
. The CDI container injects any available instance of the
Product
interface into
the
product
member variable as shown in Listing 7‐9.
LISTING 7‐9:
The PriceDiscountDecorator decorator
@Decorator
public class PriceDiscountDecorator implements Product {
@Any
@Inject
@Delegate
private Product product;
public String generateLabel() {
product.setPrice(product.getPrice() * 0.5);
product.setLabel(product.getLabel() + " (Discounted)");
return product.generateLabel();
}
// Not all methods shown
}
Finally, you must declare the decorator in
bean.xml
. Although most of the coni guration has already
been done via annotations, you still need to add some XML coni guration to make the decorator