Java Design Pattern Command

Java Design Pattern Command

This document summarizes the Command Pattern implemented in Java.

1. Java Command Pattern

Command Pattern is a Pattern that encapsulates requests (Commands) so that requests can be performed even if the requester does not exactly understand the request. Command Pattern consists of Classes that perform the following roles.

  • Receiver : A Class that performs the role of receiving requests and actually processing requests.
  • Command : A Class that performs the role of delivering specific requests to the Receiver. Command Class must implement the Command Interface and contains a Receiver Instance.
  • Invoker : A collection Class of Concrete Instances. Requesters call Command objects through the Invoker to deliver requests to the Receiver.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// receiver
public class Light{
     public Light(){}

     public void turnOn(){
        System.out.println("light on");
     }

     public void turnOff(){
        System.out.println("light off");
     }
}

// command interface
public interface Command{
    void execute();
}

// concrete command
public class TurnOnLightCommand implements Command{
   private Light theLight;

   public TurnOnLightCommand(Light light){
        this.theLight=light;
   }

   public void execute(){
      theLight.turnOn();
   }
}

public class TurnOffLightCommand implements Command{
   private Light theLight;

   public TurnOffLightCommand(Light light){
        this.theLight=light;
   }

   public void execute(){
      theLight.turnOff();
   }
}

// invoker
public class Switch {
    private Command flipUpCommand;
    private Command flipDownCommand;

    public Switch(Command flipUpCmd, Command flipDownCmd){
        this.flipUpCommand = flipUpCmd;
        this.flipDownCommand = flipDownCmd;
    }

    public void flipUp(){
         flipUpCommand.execute();
    }

    public void flipDown(){
         flipDownCommand.execute();
    }
}

// main
public class Main{
   public static void main(String[] args){
       Light light=new Light();
       Command switchUp=new TurnOnLightCommand(light);
       Command switchDown=new TurnOffLightCommand(light);

       Switch s= new Switch(switchUp, switchDown);
       s.flipUp();   // light on
       s.flipDown(); // light off
   }
}
[Code 1] Java Command Pattern

[Code 1] shows the Command Pattern implemented in Java. The Light Class performs the role of Receiver, the TurnOnLightCommand/TurnOffLightCommand Classes perform the role of Command, and the Switch Class performs the role of Invoker. You can see that in the main() function, Light On/Off operations are performed through the Switch Instance.

2. References