GofPatterns Gofpatterns





Behavioral Patterns  «Prev  Next»

Command Pattern

The Command pattern encapsulates a request in an object, which enables you to store the command, pass the command to a method, and return the command like any other object.
The figure below illustrates the Command Pattern.

Invoker aggregates an abstract Command
Invoker aggregates an abstract Command.

Command Pattern in Java

Benefits:
The following lists the benefits of using the Command Pattern:
  1. Separates the object that invokes the operation from the one that knows how to perform it.
  2. It's easy to add new commands, because you don't have to change existing classes.
When to Use:
You should use the Command pattern when:
  1. You want to parameterize objects by an action to perform.
  2. You specify, queue, and execute requests at different times.
  3. You must support undo, logging, or transactions