Command

Encapsulate request as an object

Overview

The Command pattern turns a request into a stand-alone object that contains all information about the request. This allows you to parameterize methods with different requests, delay or queue a request's execution, and support undoable operations.

Key Concepts

Command: Declares interface for executing an operation

ConcreteCommand: Binds an action to a receiver

Invoker: Asks command to carry out request

Receiver: Knows how to perform the actual work

Code Example

java
1public interface Command {
2    void execute();
3    void undo();
4}
5
6public class Light {
7    public void turnOn() { System.out.println("Light is ON"); }
8    public void turnOff() { System.out.println("Light is OFF"); }
9}
10
11public class TurnOnLightCommand implements Command {
12    private Light light;
13    
14    public TurnOnLightCommand(Light light) { this.light = light; }
15    
16    @Override public void execute() { light.turnOn(); }
17    @Override public void undo() { light.turnOff(); }
18}
19
20public class RemoteControl {
21    private Command lastCommand;
22    
23    public void submit(Command command) {
24        command.execute();
25        lastCommand = command;
26    }
27    
28    public void undoButton() {
29        if(lastCommand != null) lastCommand.undo();
30    }
31}
32
33public class Client {
34    public static void main(String[] args) {
35        Light livingRoomLight = new Light();
36        Command turnOn = new TurnOnLightCommand(livingRoomLight);
37        
38        RemoteControl remote = new RemoteControl();
39        remote.submit(turnOn);
40        remote.undoButton();
41    }
42}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Command - Behavioral Patterns | LLD | Revise Algo