2.7. The Command Pattern

The GOF book defines the intent of the command pattern as being to encapsulate a request in an object that lets you parameterize clients with different requests, queue or log requests, and support undoable operations.

The idea behind the command pattern is to provide a predictable interface without any other class that uses it having to worry about the details of execution.

In its simplest form, the command pattern consists of six elements. These are:

  • Command interface

  • Concrete command

  • Receiver

  • Client

  • Invoker

The command interface is simple and defines only one method, execute, as seen in the following pseudo-code:

package com.somedomain.somepackage{
  public interface ICommand{
  function execute():void;
  }
}

The concrete command is the class that actually implements the ICommand interface, and the receiver is the class that is the target of the operation. For example:

package com.somedomain.somepackage{
  import com.somedomain.somepackage.ICommand;
  public class TurnOnLight implements ICommand{
    private var light:Light;
    public function TurnOnLight(light:Light):void{
      this.light = light;
    }
    public function execute():void{
     this.light.turnOn();
    }
  }
}

In the preceding example, TurnOnLight is the concrete command and the Light object held in the light property of the command is the receiver.

The client is the object that instantiates the command class, and the invoker is the object that calls the execute function.

The class invoking an object that implements the command ...

Get Professional Cairngorm™ 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.