Java Reference
In-Depth Information
this.name = "Whisky";
this.price = 1.5;
}
}
The
DrinkDecorator
, shown in Listing 7-10, is the
abstract
decorator class that is inherited from the
Drink
class.
The concrete decorators
Honey
and
Spices
inherit from the
DrinkDecorator
class. It has an instance variable named
drink
, which is of the type
Drink
. This instance variable represents the
Drink
object that a decorator will decorate.
It overrides the
getName()
and
getPrice()
methods for decorators. In its
getName()
method, it gets the name of the
drink it is decorating and appends its own name to it. This is what I mean by adding functionality to a component by
a decorator. The
getPrice()
method works the same way. It gets the price of the drink it decorates and adds its own
price to it.
Listing 7-10.
An Abstract DrinkDecorator Class
// DrinkDecorator.java
package com.jdojo.io;
public abstract class DrinkDecorator extends Drink {
protected Drink drink;
@Override
public String getName() {
// Append its name after the name of the drink it is decorating
return drink.getName() + ", " + this.name;
}
@Override
public double getPrice() {
// Add its price to the price of the drink it is decorating/
return drink.getPrice() + this.price;
}
public Drink getDrink() {
return drink;
}
}
Listing 7-11 lists a concrete decorator, the
Honey
class, which inherits from the
DrinkDecorator
class. It accepts
a
Drink
object as an argument in its constructor. It requires that before you can create an object of the
Honey
class,
you must have a
Drink
object. In its constructor, it sets its name, price, and the drink it will work with. It will use the
getName()
and
getPrice()
methods of its superclass
DrinkDecorator
class.
Listing 7-11.
A Honey Class, a Concrete Decorator
// Honey.java
package com.jdojo.io;
public class Honey extends DrinkDecorator{
public Honey(Drink drink) {
this.drink = drink;
this.name = "Honey";