Command Pattern
- 다양하게 처리되어야 하는 요청과 그 대상을 캡슐화하여 모든 요청들을 같은 방식으로 처리 가능
- 요청을 보내는 쪽과 처리하는 부분이 분리가 되어 서로를 몰라도 됨
- 여러 다른 명령이 추가되어도 일관성있는 처리 가능
- ex: messageQueue
code
- Command
public interface Command { void execute(); }
- ConcreteCommand
public class LightOffCommand implements Command { Light light; public LightOffCommand(Light light) { this.light = light; } public void execute() { light.off(); } }public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); } }
- invoker
public class NoCommand implements Command { public void execute() { } }
- receiver
public class Light { String location = ""; public Light(String location) { this.location = location; } public void on() { System.out.println(location + " light is on"); } public void off() { System.out.println(location + " light is off"); } }
장단점
장점
1.단일책임원칙: 작업을 호출하는 클래스들을 작업을 수행하는 클래스들로부터 분리할 수 있음
2.개방폐쇄원칙: 기존 클라이언트 코드를 손상하지 않고 새 커맨드를 도입할 수 있음
3.실행취소,다시실행을 구현할 수 있음
4. 작업들의지연된 실행을 구현할 수 있음
5. 간단한 커맨드들의 집합을복잡한 커맨드로 조합할 수 있음
단점
- 발송자와 수신자 사이에 완전히 새로운 레이어를 도입하기 때문에
코드가 더 복잡해질 수 있음
출처
이 글은 인프런 박은종 강사님의 강의 내용을 정리하기 위하여 작성하였습니다.