A Classic Example: Menu Commands

Menus provide a classic example of the need for the COMMAND 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 ...

Get Design Patterns Java™ Workbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.