Home > Articles > Programming > Java

Java Reference Guide

Hosted by

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Command Pattern

Last updated Mar 14, 2003.

You are undoubtedly familiar with the command pattern, although you may not recognize it by name. The purpose of the command pattern is to define a set of functionality that can be executed at a later time. While this definition may sound very generic, in practice it typically consists of a command interface, and command class that implements that interface, and a process that invokes the command through its interface. The command pattern defines the following roles:

  • Client
  • Invoker
  • Receiver

The client is responsible for creating the command and initializing it with all of the information that it needs to be invoked. The invoker is responsible for determining when a command should be executed, such as in a response to a button being pressed or a menu item being selected. The receiver is an instance of the class that receives the action of the command.

The main purpose of the command pattern is to encapsulate functionality into an object and then control an application’s actions through those commands. For example, you could implement the undo functionality of an application by maintaining a stack of commands that have been executed. When the user invokes the undo functionality, the application responds by calling the command’s undo() method. Likewise, if you wanted to implement a set of macros, you could simply create an ordered collection of commands and then replay them at the user’s request.

Nothing explains the Command Pattern as well as an example, so listings 1 – 5 show the source code for a simple game that contains a game board, commands for moving up and down the game board, and a game that drives everything.

Listing 1. GameBoard.java

/**
 * The receiver, represents a game board
 */
public class GameBoard {
 private int xpos = 0;
 private int ypos = 0;
 public static final int XMAX = 10;
 public static final int YMAX = 10;

 public GameBoard() {
 }

 public int getXPos() {
  return xpos;
 }

 public void setXPos( int xpos ) {
  this.xpos = xpos;
 }

 public int getYPos() {
  return ypos;
 }

 public void setYPos( int ypos ) {
  this.ypos = ypos;
 }
}

Listing 2. Command.java

/**
 * The command interface
 */
public interface Command {
 public void execute();
 public void undo();
}

Listing 3. MoveUpCommand.java

/**
 * Command that moves the player up one space
 */
public class MoveUpCommand implements Command {
 private GameBoard gb;

 public MoveUpCommand( GameBoard gb ) {
  this.gb = gb;
 }

 public void execute() {
  int ypos = gb.getYPos();
  if( ypos < GameBoard.YMAX ) {
   gb.setYPos( ++ypos );
  }
 }

 public void undo() {
  int ypos = gb.getYPos();
  if( ypos > 0 ) {
   gb.setYPos( --ypos );
  }
 }
}

Listing 4. MoveDownCommand.java

/**
 * Command that moves the player up down space
 */
public class MoveDownCommand implements Command {
 private GameBoard gb;

 public MoveDownCommand( GameBoard gb ) {
  this.gb = gb;
 }

 public void execute() {
  int ypos = gb.getYPos();
  if( ypos > 0 ) {
   gb.setYPos( --ypos );
  }
 }

 public void undo() {
  int ypos = gb.getYPos();
  if( ypos < GameBoard.YMAX ) {
   gb.setYPos( ++ypos );
  }
 }
}

Listing 5. Game.java

/**
 * Invoker class
 */
public class Game {
 private GameBoard gb = new GameBoard();
 private Command moveUpCommand;
 private Command moveDownCommand;

 public Game() {
  moveUpCommand = new MoveUpCommand( gb );
  moveDownCommand = new MoveDownCommand( gb );
 }

 public void action() {
  // Determine what to do:
  moveUpCommand.execute();

  // or
  moveDownCommand.execute();
 }
}

Listing 1 shows the source code for the game board, which represents the receiver in Command Pattern terms. The receiver is the component that receives the actions of the command. The purpose, in its currently limited capacity, of the game board is to maintain a player’s location within the game. Presumably we would add things like walls, monsters, treasures and so forth.

Listing 2 shows the source code for the Command interface. This interface defines two methods: execute() and undo(). The sample application only uses the execute() method, but the undo() method is defined to allow the game to undo a user’s actions if required.

Listings 3 and 4 show the source code for the MoveUpCommand and MoveDownCommand, respectively. These commands update the y-position of the game board and check to make sure that the updates do not violate the constraints of the game board. They also implement the undo functionality with the same constraint checks.

Finally, listing 5 shows snippets from the source code for the Game itself. In the context of the Command Pattern, the Game is both the client and the invoker. The client functionality is contained within the constructor: it creates all commands and initializes them with a reference to the game board. The invoker functionality is contained within the action() method: as the game receives actions, it invokes the correct command. The Game class is far from complete, but it illustrates how you would could map actions to commands as well as provides an entry point to implementing undo. Consider the following additions to the Game:

private Stack commands;
...
public void action() {

 // Perform command
 Command command = CommandFactory.getCommand();
 command.execute();

 // Add the command to our stack
 commands.push( command );
}

public void undo() {
 Command command = commands.pop();
 if( command != null ) {
  command.undo();
 }
}

If we maintain our commands in a Stack then it would be a simple matter of pushing commands onto the stack as they’re being executed and popping them off if you need to undo. If you were going to try to implement undo functionality without commands, such as by interpreting their functionality and attempting to undo them yourself, the task would be far more difficult, but the Command Pattern makes it easy.

You can find Java’s use of commands littered all throughout the Swing API. For example, menu items, toolbar buttons, push buttons, text fields, and so forth, can all fire action events. Action events are handled by classes that implement the ActionListener interface, which defines an actionPerformed() method. In the previous example I focused on a Command class, but technically the Command Pattern only requires a method, which, again, can be executed by the invoker at some future time. The actionPerformed() method is therefore an example of the Command Pattern. Although if you’ve ever seriously worked on a Swing application, the best solution is to create an Action class to encapsulate all of the functionality into a single object and then reuse that object anywhere that action can occur (such as by selecting a menu item, selecting a toolbar button, or by pressing a hot key.) The point is that you’ve probably already used the Command Pattern, but maybe without knowing it.

For more examples, Wikipedia has a good description of some uses of the Command Pattern, which include the following:

  • Multi-level Undo
  • Implementing transactional behavior
  • Updating progress bars
  • Building a Wizard user interface component
  • GUI buttons and menu items (e.g. Swing)
  • Thread pools: adding commands as tasks to be executed
  • Macro recording
  • Parallel processing
  • Mobile code: passing commands from one machine to another for remote execution