Design Patterns Java™ Workbook

(Michael S) #1
Chapter 27. Decorator

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
DECORATOR. Why not?

Summary......................................................................................................................................................


When you have an object type that needs a variety of behaviors that you might compose in
various ways, the DECORATOR pattern offers a flexible alternative to creating a class for every
possible behavioral combination. The Java class libraries provide a classic example of
DECORATOR in the implementation of input and output streams. In application code, you can
apply DECORATOR 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 DECORATOR.
A design may allow runtime customization of an object's attributes and its behavior without
using DECORATOR. The intent of DECORATOR is to let you compose an object's behavior
from a collection of cooperating classes.

Free download pdf