Yes, so basically making an object that encapsulates the behavior and other information that is needed when an action takes place can be seen as using the command pattern.
The Wikipedia article linked above uses the Action
interface as an example of the command pattern in Swing. The Action
interface is a subinterface of ActionListener
, so a class that implements Action
will have to implement the actionPerformed
method.
Therefore, a class implementing Action
will be encapsulating some operations which will be performed when an action occurs. And that class itself can be seen to follow the command pattern.
When it comes to the implementation, in general, an AbstractAction
can be easier to use than implementing Action
as it has several methods that needs to be overridden. An example using AbstractAction
can be:
class MySpecialAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
// Perform operations.
}
}
The MySpecialAction
is a command pattern object -- it has the behavior it must exhibit when an action takes place. When instantiating the above class, one could try the following:
MySpecialAction action = new MySpecialAction("Special Action", mySpecialIcon);
Then, the action can be registered to multiple components, such as JButton
s, JMenuItem
s and such. In each case, the same MySpecialAction
object will be called:
JMenuItem specialMenuItem = new JMenuItem(action);
/* ... */
JButton b = new JButton(action);
In both cases, the action that is associated with each component, the button and the menu item, refer to the same MySpecialAction
action object, or command. As we can see, the MySpecialAction
object is functioning as a object following the command pattern, as it encapsulates some action to be performed at a the time when an action takes place.