- Overview
-
Table of Contents
- J2SE: Standard Java
- Java Windows NT Services
- Apache Velocity
- Advanced J2SE
- Bytecode Instrumentation
- Dynamic Languages and the JVM
- J2SE 1.5.0: "Tiger"
- Java SE 6
- Java 7
- Core Computer Science Principles in Java (Data Structures)
- Annotations
- Java Generics
- Java New I/O
- Java Sound
- Java Applets
- JavaFX
- Java SE Threading
- Resource Management Using Semaphores
- Java Atomic Operations
- JavaTemplate Pages
- Executing Templates with the JtpExecutor
- Java Cryptography Extensions (JCE)
- Java Database Connectivity (JDBC) API
- Jakarta Commons - Net Class Library
- Jakarta Commons HttpClient
- Apache POI
- Regular Expressions
- JavaMail
- Cool Tools
- Building an Really Simple Syndication (RSS) Java App
- Embedding JavaScript in Java with Rhino
- Logging with Log4J
- Inside Swing
- Swing Components
- SwingX
- Swing Styled Documents
- Web Rendering in Java Swing Applications
- Java Look-and-Feel Graphics Repository
- Java Media Framework
- Quicktime for Java
- Media in Java Review 2008
- External Multimedia in Java
- Graphs and Charts
- Holiday Special: Electronic Greeting Card
- Media Framework: Presenter Application
- Standard Widget Toolkit
- JFace
- Java Performance Tuning
- J2EE Performance Tuning
- Caches and Pools
- Java Caching System
- EHCache
- Java Compression and Decompression
- Obfuscating Java Applications
- Continuous Integration
- Load Testing
- Tomcat Clustering
- High Scalability with Terracotta
- Troubleshooting Production Performance Issues
- Enterprise Java Testing
- Automated Unit Testing with JUnit and Ant
- Unit Testing: Tips From The Trenches
- Custom Ant Tasks
- Extensible Markup Language (XML)
- Java Web Technologies
- Web Frameworks
- Struts 2
- Wicket
- JavaServer Faces
- Distributed Programming / RMI
- Behavior Tracking Servlet Filter
- Servlet Filters
- Building a Robust Java Server
- J2EE: Enterprise Java
- Spring
- Spring 3
-
Java Design Patterns
- Gang of Four
- Abstract Factory Pattern
- Factory Method Pattern
- Template Pattern
- Singleton Pattern
- Builder Pattern
- Prototype Pattern
- Adapter Pattern
- Bridge Pattern
- Composite Pattern
- Observer Pattern
- Command Pattern
- Chain-of-Responsibility Pattern
- Mediator Pattern
- Memento Pattern
- Iterator Pattern
- State Pattern
- Visitor Pattern
- Strategy Pattern
- Transfer Object Pattern
- Proxy Pattern
- Flyweight Pattern
- Decorator Pattern
- Facade Pattern
- A Real World Application
- Session Façade Pattern
- Data Access Object Pattern
- Front Controller Pattern
- Service Locator Pattern
- Design Patterns Cheat Sheet
- Books and E-Books
- Online Resources
- Official Documentation
- Model-Driven Architecture
- Enterprise Messaging with ActiveMQ
- Event-Driven Architecture
- XDoclet
- Hibernate
- Developing Standalone Database Applications with Hypersonic DB
- Project Backup
- J2EE Project: Hands-On
- Enterprise Java Beans (EJB) 3.0
- Disaster Recovery
- Java Management Extensions (JMX)
- Service-Oriented Architecture
- Web Services
- RESTful Web Services
- Web Services with Apache CXF
- Atom Syndication
- Project: Building a Web Photo Gallery
- J2ME: Micro Java
- Specialized J2ME
- Optional Packages
- Other Java Technologies
- Derivatives and Competitors
- Java, Engineered for Integration
-
Additional Resources
- The World of Java Tools
- Building Java Applications with Ant
- Managing Java Build Lifecycles with Maven
- Acceptance Testing with FitNesse
- Source Control with Subversion
- Inversion of Control and Dependency Injection
- Certification
- Roadmap: Becoming an Enterprise Java Developer
- Roadmap: Becoming an Enterprise Java Developer in 2007
- The Business of Enterprise Software
- JavaOne 2006
- JavaOne 2007
- JavaOne 2008 Wrap-Up
- JavaOne 2009 Wrap-Up
- JavaOne 2010
- JavaOne 2011
- How to Survive in a Turbulent Job Market
- How to Hire the Best Talent
- Unified Modeling Language (UML)
- Cloud Computing
- Amazon EC2 and Java
- MongoDB
- Enterprise Java in 2008 and Beyond
- Predictions for 2018
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
