Tuesday, 19 April 2016

Command pattern - Example


The simple example of Command pattern is to design a Command interface and with an execute method like this : 
public interface Command {
    public void execute();
}

Then, design multiple implementation classes and see how powerful the execute() method has been called dynamically.
In order to take advantage of Java built-in interfaces, we will design a window with a drop down menu, button commands and popup menu with command pattern.

As we know, JButton, JMenuItem and JPopupMenu have constructors accept Action type variable. Action interface extends ActionListener, which has the following hierarchy.
public interface EventLister { ... }
public interface ActionListener extends EventListener { ... }
public interface Action extends ActionListener { ... }

There is an abstract class called AbstractAction which implements Action interface. It has the following design.
public abstract class AbstractAction extends Object 
         implements Action, Cloneable, Serializable

We will create several command classes to subclass the AbstractAction class and pass them to the constructors of JButton, JMenuItem and JPopupMenu classes.
There is a request method called actionPerformed(), every command classes must implement it in order to make it work. To show the concept, we just design two actions: submit and exit. 

You may expand such design to your need in your future project.
Such action can be attached to any component, AWT or Swing.
The caption, and Icon have been designed as well as tooltips.

class ExitAction extends AbstractAction {
   private Component target;
   public ExitAction(String name, Icon icon, Component t){
       putValue(Action.NAME, name);
       putValue(Action.SMALL_ICON, icon);
       putValue(Action.SHORT_DESCRIPTION, name + " the program");
       target = t;
   }    
   public void actionPerformed(ActionEvent evt) {
       int answer = JOptionPane.showConfirmDialog(target, 
                    "Are you sure you want to exit? ", 
                    "Confirmation", JOptionPane.YES_NO_OPTION);
       if ( answer == JOptionPane.YES_OPTION) {                   
           System.exit(0);
       }
   }
}

Similar to the above exit action, the submit action is as follows : 
class SubmitAction extends AbstractAction {
   private Component target;
   public SubmitAction(String name, Icon icon, Component t){
       putValue(Action.NAME, name);
       putValue(Action.SMALL_ICON, icon);
       putValue(Action.SHORT_DESCRIPTION, name + " the program");
       target = t;
   }    
   public void actionPerformed(ActionEvent evt) {
       JOptionPane.showMessageDialog(target, "submit action clicked ");
   }
}

You can modify the program to add more commands in.
These command classes are decoupled from any program. It is very good for maintenance.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.