1 개요[ | ]
- command pattern
- 커맨드 패턴
- 명령을 클래스로 표현하는 구조
- 요청을 객체의 형태로 캡슐화하는 디자인 패턴
- 서로 요청이 다른 사용자의 매개변수, 요청 저장, 로깅, 연산 취소를 지원한다.
2 구조[ | ]
Client | 커맨드를 실행하는 객체 |
Invoker | 커맨드 실행 방법을 아는 객체 |
Command | 실행할 작업과 데이터 모음 |
Receiver | 실제 작업을 수행하는 객체 |
- 위의 왼쪽 클래스 다이어그램에서...
Invoker
클래스는 요청을 직접 구현하지 않는 대신, 요청(command.execute()
)을 수행하는Command
인터페이스를 참조한다.- 그렇게 함으로써
Invoker
와 요청을 수행하는 방법이 서로 분리된다. Command1
클래스는,Receiver1
에 액션(receiver1.action1()
)을 수행하게 함으로써,Command
인터페이스를 구현한다.
- 오른쪽 시퀀스 다이어그램은 런타임 상호작용을 나타낸다.
Invoker
객체는Command1
객체의execute()
를 호출한다.Command1
객체는 요청을 수행하는,Receiver1
객체의action1()
을 호출한다.
3 예제[ | ]
Java
Copy
/* The Command interface */
public interface Command {
void execute();
}
import java.util.List;
import java.util.ArrayList;
/* The Invoker class */
public class Switch {
private List<Command> history = new ArrayList<Command>();
public Switch() {
}
public void storeAndExecute(Command cmd) {
this.history.add(cmd); // optional
cmd.execute();
}
}
/* The Receiver class */
public class Light {
public Light() {
}
public void turnOn() {
System.out.println("The light is on");
}
public void turnOff() {
System.out.println("The light is off");
}
}
/* The Command for turning on the light - ConcreteCommand #1 */
public class FlipUpCommand implements Command {
private Light theLight;
public FlipUpCommand(Light light) {
this.theLight = light;
}
public void execute(){
theLight.turnOn();
}
}
/* The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
private Light theLight;
public FlipDownCommand(Light light) {
this.theLight = light;
}
public void execute() {
theLight.turnOff();
}
}
/* The test class or client */
public class PressSwitch {
public static void main(String[] args){
Light lamp = new Light();
Command switchUp = new FlipUpCommand(lamp);
Command switchDown = new FlipDownCommand(lamp);
Switch s = new Switch();
try {
if (args[0].equalsIgnoreCase("ON")) {
s.storeAndExecute(switchUp);
}
else if (args[0].equalsIgnoreCase("OFF")) {
s.storeAndExecute(switchDown);
}
else {
System.out.println("Argument \"ON\" or \"OFF\" is required.");
}
} catch (Exception e) {
System.out.println("Arguments required.");
}
}
}
4 같이 보기[ | ]
5 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.