Java Reference
In-Depth Information
this.price = 0.25;
}
}
Listing 7-12 lists another concrete decorator, the Spices class, which is implemented the same way as the
Honey class.
Listing 7-12. A Spices Class, a Concrete Decorator
// Spices.java
package com.jdojo.io;
public class Spices extends DrinkDecorator {
public Spices(Drink drink) {
this.drink = drink;
this.name = "Spices";
this.price = 0.10;
}
}
It is the time to see the drink application in action. Let's order whiskey with honey. How will you construct the
objects to order whiskey with honey? It's simple. You always start with creating the concrete component. Concrete
decorators are added to the concrete component. Whiskey is your concrete component and honey is your concrete
decorator. You always work with the last component object you create in the series. Typically, the last component that
you create is one of the concrete decorators unless you are dealing with only a concrete component.
// Create a Whiskey object
Whiskey w = new Whiskey();
// Add Honey to the Whiskey. Pass the object w in Honey's constructor
Honey h = new Honey(w);
// At this moment onwards, we will work with the last component we have
// created, which is h (a honey object). To get the name of the drink,
// call the getName() method on the honey object
String drinkName = h.getName();
Note that the Honey class uses the getName() method, which is implemented in the DrinkDecorator class. It will
get the name of the drink, which is Whiskey in your case, and add its own name. The h.getName() method will return
Whiskey, Honey ”.
// Get the price
double drinkPrice = h.getPrice();
The h.getPrice() method will return 1.75 . It will get the price of whiskey, which is 1.5 and add the price of
honey, which is 0.25 .
You do not need a two-step process to create a whiskey with honey drink. You can use the following one
statement to create it:
Drink myDrink = new Honey(new Whiskey());
 
Search WWH ::




Custom Search