Having fun with the command pattern

“… (with) the command pattern … an object is used to represent and encapsulate all the information needed to call a method at a later time. This … includes the … method parameters …”1 A Command can be seen as a method (using Java’s terminology) and its context (arguments and local variables), all transformed to an object.

“Basically a Command can be seen as a method turned inside out.”

Having such an object, a Command can be executed at any time in the future, placed on a stack or transferred across software system boundaries.

Commands offer interesting possibilities: Given that you define a Command’s interface providing an execute and an undo method and your software system strictly makes use of commands, you can easily provide undo functionality by putting your executed Commands onto a stack, where they wait for their undo method to be called in reverse order.

A Command’s execute (and undo) methods usually get a context passed as an argument on which the Command applies its “changes”. The executed Command “remembers” the action taken as its object state for its undo method (having the same context passed) to revert the actions taken.

public RET execute( CTX aContext ) throws E;

Above is the execute method of a generic Command defined by the refcodes-command artifact. Below is the method used when the Command provides undo functionality (called Undoable by the refcodes-command artifact):

void undo( CTX aContext ) throws E;

For a full example of how to implement undo functionality, see the refcodes-command article.

The refcodes-command artifact provides you a fairly good starting point for working with commands. Also take a look at the refcodes-jobbus artifact, being a command-bus settled on top of the refcodes-command artifact.

  1. See Command pattern (Wikipedia) ↩