[디자인 패턴] - Command
by 볼빵빵오춘기Command
요청을 객체로 캡슐화하여, 서로 다른 요청, 큐잉, 로깅, 실행 취소 등의 기능을 유연하게 처리할 수 있게 해주는 행동(Behavioral) 패턴이다.
즉, 명령을 객체화함으로써, 실행자(Invoker)와 수신자(Receiver)를 느슨하게 연결할 수 있다.
예시 코드
// Command 인터페이스
interface Command {
void execute();
}
// Receiver (명령의 실제 수행자)
class Light {
void on() {
System.out.println("불을 켰습니다.");
}
void off() {
System.out.println("불을 껐습니다.");
}
}
// Concrete Command
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.on();
}
}
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.off();
}
}
// Invoker (명령 실행을 요청하는 쪽)
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Client
public class CommandExample {
public static void main(String[] args) {
Light light = new Light();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
RemoteControl remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton(); // 불을 켰습니다.
remote.setCommand(lightOff);
remote.pressButton(); // 불을 껐습니다.
}
}
Command 패턴의 장점
요청과 실행 분리
명령을 실행하는 객체와 실행되는 객체의 결합도를 낮춘다.
실행 취소(undo), redo 가능
명령을 저장하고 되돌릴 수 있다.
명령 기록(로깅) 가능
요청을 저장하고 나중에 다시 실행할 수 있다.
매크로(Command 묶기)
여러 명령을 하나의 명령으로 묶어 처리 가능하다.
클라이언트 코드를 단순화
명령 실행만 알면 되고, 어떻게 처리되는지는 몰라도 된다.
Command 패턴의 단점
클래스 수 증가
명령마다 클래스를 생성해야 하므로 코드가 많아진다.
복잡도 증가
단순한 작업에 사용하면 오히려 구조가 복잡해질 수 있다.
Command 패턴 언제 사용하나?
사용자의 요청을 큐에 저장하거나 나중에 실행하고 싶을 때
ex) UI의 버튼 클릭 처리, 리모컨 기능 등
실행 취소(Undo) 기능이 필요할 때
ex) 텍스트 편집기, 도형 편집기
로그에 요청 내역을 기록하고 싶을 때
ex) 서버 요청 처리 기록
클라이언트가 요청의 수신자나 실행 방법을 알 필요 없게 하고 싶을 때
ex) 실행 객체를 몰라도 명령을 실행 가능하게 하고 싶을 때
정리하자면
"요청을 객체화"하여 실행, 취소, 재실행 등을 유연하게 처리할 수 있게 해주는 패턴이다.
'👩🏻💻 About 프로그래밍 > Spring, Spring boot' 카테고리의 다른 글
[디자인 패턴] - Iterator (0) | 2025.04.09 |
---|---|
[디자인 패턴] - Interpreter (1) | 2025.04.09 |
[디자인 패턴] - Chain of Responsibility (0) | 2025.04.09 |
[디자인 패턴] - Proxy (0) | 2025.04.09 |
[디자인 패턴] - Flyweight (0) | 2025.04.09 |
블로그의 정보
Hello 춘기's world
볼빵빵오춘기