Implementing the command pattern
The command pattern is useful for storing an arbitrary set of operations that can be executed at a later time. It has been used to support GUI action controls such as buttons and menus, recording macros, and supporting undo operations.
It is a behavioral design pattern where an object encapsulates the information needed to perform an operation at a later time. We will illustrate this pattern using a macro-like facility where a character can walk, run, or jump. A sequence of these actions can be saved and executed as needed.
Object-oriented solution to the command pattern
We start with the declaration of the Command
interface as shown next. It has a single method, execute
, whose intent is to execute some command and return whether it was successful or not.
public interface Command { public boolean execute(); }
The Move
interface details the actions that will be supported:
public interface Move { public boolean walk(); public boolean run(); public boolean...