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, it can be placed on a stack or it can be transferred throughout software system boundaries.

Commands offer you funny possibilities: Given you define a Command’s interface providing an execute and an undo method and your software system strictly makes use of commands, then you easily can provide undo functionality by putting your executed Commands onto a stack, where they are just waiting for having their undo method 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 see the execute method as of a (generic) Command defined by the refcodes-command artifact. See below in case the Command provides undo functionality (called Undoable by the refcodes-command artifact):

void undo( CTX aContext ) throws E;

For a full example on how to do the undo 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)