Ssup2 Blog logo Ssup2 Blog

Java로 구현하는 Command Pattern을 정리한다.

1. Java Command Pattern

Command Pattern은 요청(Command)을 캡슐화 하여 요청자가 요청에 대해서 정확히 파악하고 있지 않더라도 요청을 수행할수 있도록 만드는 Pattern이다. Command Pattern은 다음과 같은 역활을 수행하는 Class로 구성된다.

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]은 Java로 구현한 Command Pattern을 나타내고 있다. Light Class는 Recevier, TurnOnLightCommand/TurnOffLightCommand Class는 Command, Switch Class는 Invoker 역활을 수행한다. main() 함수에서 Switch Instance를 통해서 Light On/Off 동작을 수행하는 것을 확인 할 수 있다.

2. 참조