command pattern class diagram

Command Pattern with Java examples

This pattern falls under the behavioral design pattern category. In this pattern, the information inside one request is mapped to a single object and then that object is used as required. It encapsulates a whole request as an object called ‘Command’. The ‘Command’ can be identified as a materialized method call. That object often contains a batch of queued commands with rollback capabilities. Service requester, who initiates the request is not aware how the job will be completed or which requests are sent to the appropriate parties.

The GoF definition,

‘Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo of operations’

The definition highlights the importance of the pattern in several aspects. The command pattern will serve not only for a single request for one-time use. It is a way of executing a set of requests or a series of commands as well as rolling back a series of commands.

What is ‘Command’ Object?

This is the intermediary object that links the request invoker, which triggers the request and the request receiver, which handle the request by performing several operations. It does not execute any functionality but contains all the information required to perform an operation. The information can be an object, a method to apply to an object and method arguments if required. Command object will contain only one method called ‘execute()’ and it will trigger the actual operations from request receiving end. In addition, this command object act as the main interface for all the internal commands and a sequence of command objects can be assembled into a composite command. This materialization of commands as objects enable the requests to perform passing, staging, sharing and treating as table entries.

Structure of the Command Pattern: Class Diagram

 

command pattern class diagram

Components of the Command Pattern

  • Command

Represents the common interface for all concrete commands. This is the core of the contract and must contain the execute() equal method to pass the trigger.

  • Concrete Command

This class extends the command interface and implements the execute() method with actual operations to be performed in order to fulfil the client request. It also creates a binding between the action and the receiver. Often concrete command uses the external object ‘Receiver’ to store and use the required parameters to execute the methods.

  • Invoker

This is the main entry point to execute a complex set of commands. Client calls the invoker’s execute command method to access the command interface. Invoker stores a reference of a command object to trigger the operation executed when required. It is unaware of the concrete command and does not create any command objects, but instruct the available command object to carry out the request.

  • Receiver

This object knows how to perform the actual operations and carry out the actions to fulfil the request. That means it contains the business logic or data related to response creation.

  • Client

The client instantiates a concrete command object and passes those to appropriate invokers. It creates the invoker and receiver objects as well. Then it checks and decides which receiver objects link with the command objects and which commands to link with the invoker. In addition, it decides which command to execute at which points

How Does the Command Pattern Works?

The client needs to fulfil a request from an external party. The external party is identified as the receiver, but the client doesn’t know how the receiver performs the operation. The client contains the required objects to perform the request. The command is the high-level representation of the concrete command implementation. That is several concrete commands can be inside one scenario.

First, the client creates a ‘Receiver’ object and then attach it to the command object. The command object is responsible to pass the request to the appropriate ‘Receiver’ method, which caters for the request. Then, the client creates the invoker object and attach the command object to route the appropriate action. The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Receiver has the knowledge of what to do to carry out the request.

Command Pattern Example

Let’s assume a smart home electrical unit system that controls by a universal remote. There are two kinds of systems, which are operated by the universal remote. Those two are the living room light system and Air Conditioner.  We will include those two sub-systems into a super system as ‘Home Electronics’. Universal remote has two buttons as ‘On’ and ‘Off’. When the homeowner press ‘On’ both the light system and air-conditioned activates.

Let’s apply the command pattern to this scenario,

  • Command: Command interface to initiate the execution and abstract the concrete commands.
  • OnCommand: Concrete command class that implements the ‘On’ operations for the ‘HomeElectronics’
  • OffCommand: Concrete command class that implements the ‘Off’ operations for the ‘HomeElectronics’
  • UniversalRemote: UniversalRemote class will maintain all the receivers and will provide a method to identify the currently active receiver
  • HomeElectronics: Parent class for ‘LightSystem’ and ‘Airconditioner’ home electronic systems
  • LightSystemReceiver: Act as a ‘Receiver’ object for the scenario, contains actual method implementations to execute the required functions
  • AirconditionReceiver: Act as the ‘Receiver’ object for the scenario, contains actual method implementations to execute the required functions
  • ButtonInvoker: This class act as the invoker for any action
  • HomeOwnerClient: The client who needs the service of receivers

How to Implement the Pattern in Example

  1. Define the base interface ‘Command’ with the ‘execute()’ similar method
  2. Create concrete classes implementing the ‘Command’ interface and including a ‘Receiver’ object instance with appropriate arguments to perform the concrete execution
  3. Include an instance of ‘Command’ inside the ‘Invoker’ object
  4. The client creates the ‘Command’ and ‘Invoker’ instances and passes a command instance to the invoker instance
  5. Then invoker decides and triggers the ‘execute()’ method at the required time
  6. Finally, receivers get the signal and execute the actual methods to cater the request

High-Level Diagram

 

command pattern example

Code Samples

Command.java

OnCommand.java

OffCommand.java

HomeElectronics.java

AirconditionReceiver.java

LightSystemReceiver.java

UniversalRemote.java

ButtonInvoker.java

HomeOwnerClient.java

When to use the Command Pattern

  • When the requests need to be handled in certain time occurrences and according to different triggers situations
  • When the client and the service provider needs to be decoupled
  • When there is a need for rollback functionality for certain operations
  • When the history of requests required
  • When there is a need to add new commands
  • When there is a need for parameterizing objects according to an action

 

Source Code

You can find the source code on github : https://www.javagists.com/command-pattern-java-examples

T Tak

Hey ! I'm Tak. I'm a software developer since 2008 and been programming since I was 17 years, started with pascal. I love programming, teaching and building stuff on web.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.