Command: Introduction

Get a brief introduction to the Command design pattern.

The Command design pattern isolates an operation in its own object. This makes such an operation reusable, so we don’t have to construct a brand new logic every time we need to perform such an operation.

The most popular way of using Command is in database operations. A Command object contains all the necessary information to perform some action that would modify the data (insertion, update, deletion, etc.). Then, if we need to perform such an operation on a particular database table, all we have to do is just reuse this object and maybe modify some of its parameters. We won’t have to write complex logic involving object-relationship mappers or direct database queries.

Summarized concept of the Command design pattern

The Command pattern can be summarized as follows:

  • There’s a Command interface that describes the behavior that each command should have. Usually, it only has one method, which executes the action.
  • If multiple related commands are needed, it makes sense to add a Command abstract class with shared functionality.
  • Each Concrete Command class accepts parameters in its constructor and implements the method that executes the action.
  • Because Command accepts constructor parameters, it’s intended to be a single-use object.
  • Optionally, there could be an Invoker object, which decides which commands to execute.

Get hands-on with 1200+ tech skills courses.