Java Reference
In-Depth Information
Chapter 24. Command
Polymorphism lets you encapsulate a request, or a command as an object: Establish the
signature of a method to call, and vary the effect of calling the method by varying the
implementation. The C OMMAND pattern establishes a method signature, most often
execute() or perform() , and lets you define various implementations of this interface.
This lets you encapsulate a request as an object, so that you can parameterize clients with
different requests, queue, time, or log requests, and require companion operations, such as
undo() .
A Classic Example: Menu Commands
Menus provide a classic example of the need for the C OMMAND pattern. When you add
a menu to an application, you have to configure the menu with words that describe actions
that the user can choose, such as Save and Load. You also have to configure the menu so that
it can take action, calling a method in response to a user's click. However, the developers who
wrote the code for the JMenuItem class had no way of knowing what action you will want
when an item is selected.
How can you arrange for a class to call a method of yours when the user clicks? The answer is
to use polymorphism: Make the name of the operation fixed, and let the implementation vary.
For JMenuItem , the operation is actionPerformed() . When the user makes a choice,
a JMenuItem object calls the actionPerformed() method of any object that has
registered as a listener.
CHALLENGE 24.1
The mechanics of Java menus make it easy to apply the C OMMAND pattern, but they
do not require that you organize your code as commands. In fact, it is common to
develop an application in which a single object listens to all the events in a GUI.
What pattern does that follow?
When you develop a Swing application, you may want to register a single listener for all of an
application's GUI events, especially if the GUI components interact. For menus, however, this
may not be the best pattern to follow. If you use a single object as a listener, that object has to
sort out which GUI object generated an event. If you have many menu items that take
independent actions, it may be better to apply C OMMAND .
The method that a menu item calls when a user selects it is actionPerformed() , but you
might think of it as execute() . When you create a JMenuItem object, you can supply it
with a command to execute when the user selects the item. Your task is to create an object
that implements actionPerformed() with a method that takes an action that corresponds
to the user's command. Rather than define a new class to implement this one little behavior, it
is often better to use an anonymous class to outfit menu items with action commands.
Search WWH ::




Custom Search