Java Reference
In-Depth Information
b.addMouseListener
(
new MouseAdapter()
{
public void mouseEntered(MouseEvent e)
{
b.setBackground(Color.cyan);
b.repaint();
}
public void mouseExited(MouseEvent e)
{
b.setBackground(Color.lightGray);
b.repaint();
}
}
);
b.setBackground(Color.lightGray);
p.add(b);
SwingFacade.launch(p, " Rollover");
}
}
CHALLENGE 27.5
The
ShowListen
program outfits a
JButton
object at runtime with a new
behavior, interacting with the cursor position. But this design is not an instance of
D
ECORATOR
. Why not?
Summary
When you have an object type that needs a variety of behaviors that you might compose in
various ways, the D
ECORATOR
pattern offers a flexible alternative to creating a class for every
possible behavioral combination. The Java class libraries provide a classic example of
D
ECORATOR
in the implementation of input and output streams. In application code, you can
apply D
ECORATOR
to set up function hierarchies. This lets you create a large family of
function objects from a fixed set of function classes.
It is easy to mistake examples of "decoration" in a design as instances of D
ECORATOR
.
A design may allow runtime customization of an object's attributes and its behavior without
using D
ECORATOR
. The intent of D
ECORATOR
is to let you compose an object's behavior
from a collection of cooperating classes.