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 ...

Get Learning Java Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.