JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

How to implement the Command Design Pattern in Java

Author:JIYIK Last Updated:2025/03/19 Views:

Hello everyone, today, we will learn an important design pattern which is often overlooked by Java developers. Yes, I am talking about the Command pattern which helps us write flexible and loosely coupled code to implement actions and events in our application. In short, the Command design pattern is used to separate the request for an action from the object that actually performs the action. This decoupling between the Invoker and Receiver objects provides a uniform way of performing different types of actions. This decoupling is achieved using the Command object which is usually an execute()interface with methods like .

The Requestor or Invoker only knows about the Command object and does not care about the actual object that handles the request, which may be different. This transparency leads to cleaner code on the caller side and also gives the opportunity to do something clever on the command side.

Our Command object can be as dumb as simply delegating the request to the Receiver , or as smart as recording the last command to perform UNDO and REDO functions.

The Command pattern ensures that our code complies with the Open Closed Design Principle, the OSOLID of Design Principle , which means that adding new commands will be very easy, creating a new implementation of the interface and not affecting the Invoker code.Command

The command pattern is particularly popular in GUI applications where we use many commands like open, close, save, cut, copy, paste and corresponding UNDO and REDO operations.


1. Command Mode Terminology

Before we go further to implement the Command pattern in Java, let us first get familiar with the terminology used in the pattern.

  • Client - creates a specific command object and uses the Receiver configuration
  • Invoker - who holds the command and calls the execute() method on the Command object
  • Receiver - the actual object that handles the request
  • Command - interface, which accepts the caller's request and delegates to the receiver
  • ConcreteCommand - Implementation of the Command interface to perform a specific task

UML diagram of the Command design pattern

Here is a UML diagram of the Command design pattern which will make things clearer.

We can see that the Client has a CallbackInterfacereference to , which has a common method execute(). Each command implements this interface and provides an implementation, which simply delegates to the actual object to do the work.

The important thing is that the client is unaware of the Actual objects that perform operations on behalf of these commands. This decoupling results in flexible code, and new commands can be easily added without affecting the client code.

 

Command design pattern UML diagram
Command design pattern UML diagram

 

This is possible because the Open/Closed design principle makes the code open for extension but closed for modification.


2. Command Design Pattern in Java - Example

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

This class represents the client side of the command pattern

Client.java

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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
        menu.runCommand("Create");
        menu.runCommand("Delete");
    }
}

This class represents a command

Menu.java

public class Menu{
    Map menuItems = new HashMap();
   
    public void setCommand(String operation, Command cmd){
        menuItems.put(operation, cmd);
    }
   
    public void runCommand(String operation){
        menuItems.get(operation).execute();
    }
 
}

Indicates the command interface:

Command.java

interface Command {
    public void execute();
}

Some implementations of the command interface, this command will delete the file

DeleteCommand.java

public class DeleteCommand implements Command {
    @Override
    public void execute() {
        System.out.println("Deleting file");
    }
}

Another implementation of the command interface for creating files:

CreateCommand.java

public class CreateCommand implements Command {
    @Override
    public void execute() {
        System.out.println("Creating file");
    }
}

We can see that we have created two commands Createand using the Command pattern Delete. It is also one of the GOF patterns.

We can see that Command is an interface, CreateCommandand DeleteCommandboth implement the interface and implement execute()the method to place the logic that the command should perform.


3. Real-world examples of the Java Command pattern

One of the best ways to learn and understand design patterns is to explore as many real-life examples as possible. Seeing how a specific framework like Spring, a project, or a library uses a pattern can help develop the insight needed to identify use cases where the pattern can be applied.

Whenever I learn a new design pattern, I always look for its usage in the core Java libraries. Since every Java programmer uses JDK libraries every day, there are more chances to connect to examples than any random trivial example.

Two examples of the command pattern in the JDK are the java.lang.Runnableand javax.swing.Actioninterfaces. If we look closely, we can see that the thread pool executor is an invoker of the Runnable command.


4. Benefits of Command Design Pattern

As we have seen in this article, the main benefit of using the command pattern in Java is the decoupling of the caller of the command from the object that performs the actual processing. By decoupling them and using the introduction of the Command object, we have created a design that can track every state that is changed through the Command object.

This knowledge can be used for useful purposes such as implementing UNDO and REDO operations, logging or queuing of requests, etc. In short, the Command design pattern provides the following advantages:

  1. Encapsulates request processing.

  2. Decouples the client from the objects that actually handle the request and provides a uniform way to perform similar tasks.

  3. Since the command pattern encapsulates a request, it can be used to record status, implement undo and redo functionality, queue requests, etc.

  4. The Command pattern makes it easy to add new commands. It also follows the Open Closed design principle, which means that new functionality is added by creating new code. Since request processing is transparent to the Invoker, adding new commands does not require changes on their side.


5. Disadvantages of the command pattern

Like any other design decision, the command pattern involves trade-offs. If we have a lot of commands, as in major GUI applications like Eclipse or popular Java IDEs like IntelliJIDEA, we may end up with a lot of small command classes.

Although similar functionality can be grouped into several classes, each method performs a task for a specific command.

By the way, using the command pattern results in readable, maintainable, and extensible code, so this cost is worth paying.

That's all about the Command pattern and object-oriented programming in Java. Use the Command pattern to encapsulate request processing and separate the invocation of a method from the object that actually handles the request.

The command design pattern can also be used to do some clever things instead of just delegating the request to the receiver, e.g. we can log and queue requests for processing, can perform undo operations, and can perform pre-processing operations such as logging requests for auditing etc.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Java Decorator Design Pattern Example

Publish Date:2025/03/19 Views:115 Category:ALGORITHM

Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is alway

How to use the State Design Pattern in Java?

Publish Date:2025/03/19 Views:143 Category:ALGORITHM

The State design pattern is a behavioral pattern. The State pattern looks similar to the Strategy pattern, but it helps in managing the object states so that they behave differently in different states. In this example, we will take a famou

Adapter vs Decorator vs Facade vs Proxy Design Pattern in Java

Publish Date:2025/03/19 Views:67 Category:ALGORITHM

There are some striking similarities between the Adapter, Decorator, Facade, and Proxy design patterns as they all use composition and delegation to solve problems. The Adapter pattern wraps an interface and delegates calls to it. Decorator

Observer Design Pattern in Java

Publish Date:2025/03/19 Views:70 Category:ALGORITHM

Observer design pattern in Java is a basic core Java pattern where the Observer monitors any changes in the state or properties of the Subject . For example, a company updates all shareholders about any decision taken by them here the compa

How to use Composite Design Pattern in Java?

Publish Date:2025/03/19 Views:179 Category:ALGORITHM

Hello Java programmers, if you want to learn about Composite Design Pattern in Java , such as how to implement Composite Design Pattern and when to use it, then you have come to the right place. In this article, we will discuss Composite De

How to find the IP address of the local host in Java

Publish Date:2025/03/17 Views:98 Category:NETWORK

The Java Networking API provides a way to find the local host IP address from a Java program using the java.net InetAddress class. It is rare that you need the local host IP address in a Java program. Most of the time, I use the Unix command to find t

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Do you understand JavaScript closures?

Publish Date:2025/02/21 Views:111 Category:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

Publish Date:2025/02/21 Views:183 Category:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial