에릭 프리먼 님의 "헤드퍼스트 디자인 패턴" 책을 정리한 포스팅 입니다
1. 커맨드 패턴
- 요청자와 수행자를 분리하는 패턴
- 요청을 하나의 객체로 캡슐화하여, 서로 다른 요청을 매개변수로 처리
요소
구성요소 | 역할 설명 |
Receiver |
실제 작업을 수행하는 객체
|
Command |
작업을 캡슐화한 인터페이스 또는 클래스
|
Invoker |
커맨드 객체를 받아 실행을 요청하는 객체
|
장점
- 요청을 객체로 기능 확장 (저장, 취소, 재실행 등)
- 요청 내역을 유연하게 구성 가능 (큐잉, 로깅, 트랜잭션 처리 등)
2. 예제: 리모컨
리모컨 (Receiver)
예제) RemoteControl
더보기
public class RemoteControl {
Command[] onCommands, offCommands;
Command undoCommand;
public RemoteControl() {
onCommands = new Command[7];
offCommands = new Command[7];
Command noCommand = new NoCommand();
for (int i = 0; i < onCommands.length; i++) { onCommands[i] = offCommands[i] = noCommand; }
undoCommand = noCommand;
}
public void setCommand(int slot, Command onCommand, Command offCommand) {
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot) {
onCommands[slot].execute();
undoCommand = onCommands[slot];
}
public void offButtonWasPushed(int slot) {
offCommands[slot].execute();
undoCommand = offCommands[slot];
}
public void undoButtonWasPushed() { undoCommand.undo(); }
}
명령 (Command)
- 명령 내용 캡슐화
예제) Command
더보기
public interface Command {
void execute();
void undo();
}
메서드 | 설명 | 역할 |
execute() | 명령을 실행 |
Invoker가 이 메서드를 호출해 Receiver의 작업 수행
|
undo() | 명령 실행을 취소 또는 되돌림 |
이전 상태로 롤백할 수 있도록 지원
|
예제) LightOnCommand
더보기
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) { this.light = light; }
public void execute() { light.on(); }
public void undo() { light.off(); }
}
기기 (Invoker)
3. 활용: 작업 큐
활용 방식 | 설명 |
작업 큐 (Command Queue) |
명령 요청을 큐에 저장하여 비동기 처리 가능 → 순차 실행, 나중에 실행 등 제어 가능
|
호출자-수신자 분리 |
Invoker(호출자)와 Receiver(실제 수행자)를 분리함으로써 유연하고 확장 가능한 구조 구현 가능
|
행동 복구 (Undo/Redo) |
명령을 저장해두고 나중에 되돌리기(Undo) 또는 재실행(Redo) 기능 구현 가능
|
행동 복구 메서드
메서드 | 설명 |
store() |
작업 히스토리를 직렬화하여 디스크 등에 저장
|
load() |
저장된 작업 히스토리를 역직렬화하여 애플리케이션 실행 시 복원 가능
|
execute() |
불러온 작업 히스토리를 순서대로 실행하여 앱 상태를 복구하거나 재현
|
'Java > Design Pattern' 카테고리의 다른 글
[헤드퍼스트 디자인 패턴] 7-2. 퍼사드 패턴 (0) | 2024.12.17 |
---|---|
[헤드퍼스트 디자인 패턴] 7-1. 어댑터 패턴 (0) | 2024.12.17 |
[헤드퍼스트 디자인 패턴] 5. 싱글턴 패턴 (1) | 2024.12.16 |
[헤드퍼스트 디자인 패턴] 4. 팩토리 메서드 패턴 (0) | 2024.12.16 |
[헤드퍼스트 디자인 패턴] 3. 데코레이터 패턴 (1) | 2024.12.16 |