Command Pattern 이란?
실행될 기능을 캡슐화 → 호출자(invoker) 클래스와 수신자(Receiver) 클래스 사이의 의존성을 제거하는 패턴
1) 이벤트가 발생했을 때 실행될 기능이 다양하면서도 변경이 필요한 경우 유용
2) 이벤트를 발생시키는 클래스를 변경하지 않고 재사용하고자 할 때 유용
- 호출자(invoker) 클래스: 기능의 실행을 요구
- 수신자(Receiver) 클래스: 실제 기능을 실행
Command Pattern 구현 예시
public interface Command {
public abstract void execute();
}
public class Button { // invoker
private Command theCommand;
public Button(Command theCommand){
setCommand(theCommand);
}
public void setCommand(Command newCommand){
this.theCommand = newCommand;
}
public void pressed() {
theCommand.execute();
}
}
public class Lamp { // Receiver
public void turnOn(){
System.out.println("Lamp On");
}
public void turnOff(){
System.out.println("Lamp off");
}
}
public class LampOnCommand implements Command { //ConcreteCommand
private Lamp theLamp;
public LampOnCommand(Lamp theLamp){
this.theLamp = theLamp;
}
public void execute(){
theLamp.turnOn();
}
}
public class LampOffCommand implements Command { //ConcreteCommand
private Lamp theLamp;
public LampOffCommand(Lamp theLamp){
this.theLamp = theLamp;
}
public void execute(){
theLamp.turnOff();
}
}
public class Client {
public static vodi main(String[] args){
Lamp lamp = new Lamp();
Command lampOnCommand = new LampOnCommand(lamp);
CommandLampOffCommand = new LampOffCommand(lamp);
Button button1 = new Button(lampOnCommand);
button1.pressed(); // 버튼 누르면 램프 켜짐
button1.setCommand(lampOffCommand);
button1.pressed(); // 버튼 누르면 램프 꺼짐
}
}
'Design pattern' 카테고리의 다른 글
[Design Pattern] Decorator Pattern (0) | 2022.08.10 |
---|---|
[Design Pattern] Observer Pattern (0) | 2022.08.04 |
[Design Pattern] State Pattern (0) | 2022.07.25 |
[Design Pattern] Singleton Pattern (0) | 2022.07.20 |
[Design Pattern] Strategy pattern (0) | 2022.07.13 |