The Command Design Pattern

The command design pattern is a behavioral design pattern. This pattern focuses on encapsulating all the data and related actions of an object. This design pattern allows separating the objects that produce the behavior and the objects that consume them.

The command design pattern consists of 4 major things:

  • The command interface.
  • The concrete classes that implement the command interface.
  • The request class.
  • The Broker or the orchestrator class.

Let’s dive into the code to understand the concepts better.

  • The first step is to create a command interface which the executors can implement.
public interface Command {
    public void execute();
}
  • The request class which has all the data and methods related to an object.
public class Greet {
    private static final String HELLO = "Hola!";
    private static final String BYE = "Adios!";
    public void hey() {
        System.out.println(HELLO);
    }
    public void bye() {
        System.out.println(BYE);
    }
}
  • The concrete classes that implement the Command interface and call necessary functions from the Request class.
public class SayHi implements Command {
    Greet greet;
    public SayHi(Greet greet) {
        this.greet = greet;
    }
    @Override
    public void execute() {
        greet.hey();
    }
}
public class SayBye implements Command {
    Greet greet;
    public SayBye(Greet greet) {
        this.greet = greet;
    }
    @Override
    public void execute() {
        greet.bye();
    }
}
  • The orchestrator or the broker class.
import java.util.ArrayList;
import java.util.List;
// This is the orchestrator which helps us take all the commands
// we want to execute and adds them to a list after which we can
// execute all of them
public class Orchestrator {
    List<Command> commandList = new ArrayList<>();
    public void addCommandToList(Command command) {
        commandList.add(command);
    }
    public void executeAllCommands() {
        commandList.forEach(Command::execute);
    }
}
  • The main class that executes everything.
public class Main {
    public static void main(String[] args) {
        // The Greet object has the commands that we need to execute
        Greet greet = new Greet();
        // The Orchestrator object will help add commands to list and execute them
        Orchestrator orchestrator = new Orchestrator();
        // These are the commands we want to be executed
        Command sayHi = new SayHi(greet);
        Command sayBye = new SayBye(greet);
        orchestrator.addCommandToList(sayHi);
        orchestrator.addCommandToList(sayBye);
        orchestrator.executeAllCommands();
    }
}

Now don’t be so lazy! Try to run the code above and find out what the output is 🙂

No Comments

Post A Comment