Java Reference
In-Depth Information
When a method is called on a concrete decorator, it takes some actions and calls the method on the component
it encloses. The decorator may decide to take its action before and/or after it calls the method on the component.
This way, a decorator extends the functionality of a component. This pattern is called a decorator pattern because the
decorator class adds functionality (or decorates) the component it encloses. It is also known as the
wrapper
pattern
for the same reason: it encloses (wraps) the component that it decorates.
The decorator has the same interface as the concrete components because both of them are inherited from the
common superclass,
Component
. Therefore, you can use a
Decorator
object wherever a
Component
object is expected.
Sometimes decorators add additional functionalities by adding new methods that are not present in the component,
as shown in the class diagram:
newMethodB()
,
newMethodC()
and
newMethodD()
.
Let's apply this discussion about the generic class diagram of the decorator pattern to model classes for your
drink application. The class diagram is shown in Figure
7-2
.
Figure 7-2.
The class diagram for the drink application based on the decorator pattern
In the drink application,
Rum
,
Vodka,
and
Whiskey
are the concrete components (main drinks).
Honey
and
Spices
are the two decorators that are added to decorate (or to change the flavor) of the main drinks.
The
Drink
class, shown in Listing 7-6, serves as the
abstract
common ancestor class for the main drinks and
decorators. The
name
and
price
instance variables in the
Drink
class hold the name and price of a drink; the class also
contains the getters for these instance variables. These methods define the common interface for the main drinks as
well as flavors.