Thursday, May 19, 2016

Command design Pattern in Java with Example

In simple words, Command design pattern is used to separate a request for an action from the object which actually performs the action. This decoupling between Invoker and Receiver object provides a uniform ways to perform different types of actions. This decoupling is achieved using a Command object, which is usually an interface with methods like execute(). The Requestor or Invoker only knows about Command object, and doesn't care of the actual object which process the request, which can be different. This transparency leads clean code on Invoker side and also enables opportunity to do several smart things on Command side. Your Command object can be as dumb as simply delegating request to Receiver and can be as smart as recording last command for performing UNDO and REDO functionality.

The Command pattern ensures that your code is compliant with open closed design principle, which means adding a new command would be very easy, creating a new implementation of Command interface and doesn't affect the Invoker code.

Command pattern is particularly popular in GUI applications, where we use lots of commands e.g. Open, Close, Save, Cut, Copy, Paste and corresponding UNDO and REDO operations. You can also see classic book Head First Design Pattern, it also covers command pattern and recently been updated to cover Java SE 8 as well.

Command Pattern Terminology

Before going further and implementing a command pattern in Java, let's get familiar with terminology used in this pattern.

Client - Creates Concrete Command Object and configure with Receiver
Invoker - Who hold command and calls execute() method on Command object
Receiver - Actual object, which process the request
Command - Interface, which take request from Invoker and delegates to Receiver
ConcreteCommand - implementation of Command interface for doing a particular task

UML Diagram of Command Design Pattern
Here is the UML diagram of Command Design Pattern, which will make things more clear.

command design pattern in Java - UML diagram

Command design Pattern in Java - Example

Here is our sample program to demonstrate how to use command pattern in Java.

This class represent Client of Command pattern

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 * Java program to implement Command design pattern with example.
 * @author Javin Paul
public class Client {

    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String args[]) {
      // Client creates Invoker object, command object and configure them 
      Menu menu = new Menu();
      menu.setCommand("Create", new CreateCommand());
      menu.setCommand("Delete", new DeleteCommand());
      //Invoker invokes command

Creating file
Deleting file

This class represents a command 

 * Invoker class, which holds command object and invokes method
public class Menu{
    Map menuItems = new HashMap();
    public void setCommand(String operation, Command cmd){
        menuItems.put(operation, cmd);
    public void runCommand(String operation){

An interface to represent commands :

 * Command interface for implementing concrete command
interface Command{
    public void execute();

Some implementation of command interface, this command will delete files

 * Concrete command to delete files
public class DeleteCommand implements Command{

    public void execute() {
        System.out.println("Deleting file");

Another implementation of command interface to create files :

 * Concrete command to create file
public class CreateCommand implements Command{
    public void execute() {
        System.out.println("Creating file");

You can see we have created two commands Create and Delete by using Command pattern. It's one of GOF pattern as well.  You can see Command is an interface and both CreateCommand and DeleteCommand implement that interface and implements execute() method to put the logic of what command is supposed to do.

Real world Examples of Command Pattern in Java

One of the best way to learn and understand design pattern is exploring as many real life examples as possible. Seeing, how a particular framework, project or library uses a pattern helps to develop an insight required to identify use cases, where a pattern can be applied.

Whenever, I learn a new design pattern, I always look in core Java library for it's uses. Since every Java programmer uses JDK library daily basis, chances of connecting to an example is more than any random trivial example.

Two of the Command pattern examples from JDK are java.lang.Runnable and javax.swing.Action interface. Thread Pool executors are invoker of Runnable commands.

You can also see Head First design pattern 2nd edition for more real world examples of command design pattern in Java. One of the best book to learn object oriented design patterns.

how to implement command design pattern in Java

Benefits of Command Design Pattern

As we have seen in this article, main benefit of using Command pattern in Java is decoupling Invoker of a command from the object, which does the actual processing. By decoupling them and using introducing Command object, we create a design which can keep track of every state changed via Command objects.

This knowledge can be used for useful purpose e.g. implementing UNDO and REDO operations, recording or queuing of request etc. In short command design pattern provides following advantages :

1) Encapsulate request processing.

2) Decouples clients from object which actually process request and provide a uniform way to perform similar task.

3) Since Command pattern encapsulate request, It can be used to record state, implement Undo and redo functionality, Queuing a request etc.

4) Command Pattern makes it easy to add new commands. It also follows Open Closed design principle, where new functionality is added by creating new code. Since request processing is transparent to Invoker, adding a new command doesn't require a change on there side.

Disadvantage of Command Pattern

Like any other design decision, Command pattern also involves tradeoffs. If you have lot of commands, just like in a major GUI application e.g. IDE, you might end up with lots of small command classes.

Though similar functionality can be grouped into couple of classes with each method performing task for a particular command.  By the way, using Command pattern result in readable, maintainable and extensible code, so this cost is worth paying.

You can also see Design Patterns: Elements of Reusable Object-Oriented Software - the all time classic book on GOF design pattern to learn more about command design pattern.

why use command design pattern

That's all about Command pattern in Java and Object oriented programming. Use Command pattern to encapsulate request processing and separating invocation of a method from the object, which actually process that request.

The Command design pattern can also be used for doing smart things instead of just delegating request to Receiver, e.g. you can record and queue up the request for processing, can perform undo operations and can perform pre-processing operation e.g. logging request for auditing etc.

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
SOLID Principles of Object Oriented Design


Anonymous said...

Does command pattern has a real world usage in finance and insurance domain? I see it is more useful to implements command and action hence more suitable for game programming domain, and particularly in GUI application.

KR¡S─ŽNA SON! said...

what is Receiver in this program...

Anonymous said...

Which is Receiver Class in this program

Anonymous said...

Menu class

Post a Comment