Java Reference
In-Depth Information
By using the above coding style, you get a feeling that Honey is really enclosing (or decorating) Whiskey . You
ordered a drink: whiskey with honey. Therefore, it is better to store the reference of the final drink to a Drink variable
( Drink myDrink ) rather than a Honey variable ( Honey h ). However, if the Honey class implemented some additional
methods than those inherited from the Drink class and you intended to use one of those additional methods, you
need to use a variable of the Honey class to store the final reference.
// If our Honey class has additional methods, which are not defined in Drink
// class, store the reference in Honey type variable
Honey h = new Honey(new Whiskey());
How would you order a drink of whiskey with two servings of honey? It's simple. Create a Whiskey object, enclose
it in a Honey object, and enclose the Honey object in another Honey object, like so:
// Create a drink of whiskey with double honey
Drink myDrink = new Honey(new Honey(new Whiskey()));
Similarly, you can create a drink of vodka with honey and spices, and get its name and price as follows:
// Create a drink of vodka with honey and spices
Drink myDrink = new Spices(new Honey(new Vodka()));
String drinkName = myDrink.getName();
double drinkPrice = myDrink.getPrice();
Sometimes reading the construction of objects based on the decorator pattern may be confusing because of
several levels of object wrapping in the constructor call. You need to read the object's constructor starting from the
innermost level. The innermost level is always a concrete component and all subsequent levels will be concrete
decorators. In the previous example of vodka with honey and spices, the inner most level is the creation of vodka, new
Vodka(), which is wrapped in honey, new Honey(new Vodka()) , which in turn is wrapped in spices, new Spices(new
Honey(new Vodka())) . Figure 7-3 depicts how these three objects are arranged. Listing 7-13 demonstrates how to use
your drink application.
The getName() and getPrice() methods are
called on the outermost component, which
forwards the request to the next level.
Sp ices
Honey
Vo dk a
Figure 7-3. The arrangement of components in the decorator pattern
Listing 7-13. Testing the Drink Application
// DrinkTest.java
package com.jdojo.io;
public class DrinkTest {
public static void main(String[] args) {
// Have Whiskey only
Drink d1 = new Whiskey();
printReceipt(d1);
 
Search WWH ::




Custom Search