Command Pattern




The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.


Example
public interface Command {


 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
 public void execute();
}
==========
public interface Light {
 public void on();
 public void off();
}
==========
public class LightOff implements Command{
 private Light light;
 public LightOff(Light light) {
  this.light = light;
 }
 
 public void execute(){
  System.out.println("OFF command is Fired");
  light.off();
 }
}
==========
public class LightOn implements Command{
 private Light light;
 LightOn(Light light){
  this.light = light;
 }
 
 public void execute(){
  System.out.println("ON command is Fired");
  light.on();
 }
}
==========
public class Bulb implements Light{
 @Override
 public void on() {
  System.out.println("Bulb is ON");
 }

  @Override
 public void off() {
  System.out.println("Bulb is OFF");
 }
}
==========
public class TubeLight implements Light {
 public void on(){
  System.out.println("TubeLight is ON");
 }
 
 public void off(){
  System.out.println("TubeLight is OFF");
 }
}
==========
public class SwitchBoard {
 Command myCommand;
 public void setCommand(Command myCommand){
  this.myCommand = myCommand;
 }
 
 public void pressSwitch(){
  myCommand.execute();
 }
}
==========
public class CommandFlight {
 public static void main(String[] bags){
  SwitchBoard switchBoard = new SwitchBoard();
  
  TubeLight tubeLight = new TubeLight();
  LightOn lightOnCommand = new LightOn(tubeLight);
  LightOff lightOffCommand = new LightOff(tubeLight);
  
  switchBoard.setCommand(lightOnCommand);
  switchBoard.pressSwitch();

   switchBoard.setCommand(lightOffCommand);
  switchBoard.pressSwitch();

   Bulb bulbLight = new Bulb();
  
  lightOnCommand = new LightOn(bulbLight);
  switchBoard.setCommand(lightOnCommand);
  switchBoard.pressSwitch();
  
  lightOffCommand = new LightOff(bulbLight);
  switchBoard.setCommand(lightOffCommand);
  switchBoard.pressSwitch();
 }
}