Command Pattern

요청을 객체의 형태로 캡슐화하여 나중에 사용할 수 있도록 하는 행동 디자인 패턴
요청을 하는 객체와 그 요청을 수행하는 객체를 분리한다.
이를 통해 요청을 큐에 저장하거나, 로그를 남기거나, 작업을 취소하는 등의 부가적인 기능을 쉽게 추가할 수 있다.

특징

주요 구성요소

  1. Command: 실행될 작업을 캡슐화하는 인터페이스
  2. ConcreteCommand: Command 인터페이스를 구현하여 특정 작업을 수행하는 클래스
  3. Invoker: Command 객체를 실행하는 클래스
  4. Receiver: 실제 작업을 수행하는 클래스
  5. Client: Command 객체를 생성하고 Invoker 에게 전달하는 클래스

사용사례

장점

단점

주의사항 및 고려사항

예시

Python

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
from abc import ABC, abstractmethod
from typing import List
import time

# Receiver 클래스들
class Light:
    def __init__(self, location: str):
        self.location = location
        self.is_on = False
        self.brightness = 0

    def turn_on(self) -> None:
        self.is_on = True
        print(f"{self.location} light is now on")

    def turn_off(self) -> None:
        self.is_on = False
        print(f"{self.location} light is now off")

    def dim(self, level: int) -> None:
        self.brightness = level
        print(f"{self.location} light dimmed to {level}%")

class Thermostat:
    def __init__(self, location: str):
        self.location = location
        self.temperature = 20

    def set_temperature(self, temperature: float) -> None:
        self.temperature = temperature
        print(f"{self.location} thermostat set to {temperature}°C")

# Command 인터페이스
class Command(ABC):
    @abstractmethod
    def execute(self) -> None:
        pass

    @abstractmethod
    def undo(self) -> None:
        pass

# Concrete Command 클래스들
class LightOnCommand(Command):
    def __init__(self, light: Light):
        self.light = light
        self._prev_state = None

    def execute(self) -> None:
        self._prev_state = self.light.is_on
        self.light.turn_on()

    def undo(self) -> None:
        if self._prev_state is False:
            self.light.turn_off()

class LightDimCommand(Command):
    def __init__(self, light: Light, level: int):
        self.light = light
        self.level = level
        self._prev_level = None

    def execute(self) -> None:
        self._prev_level = self.light.brightness
        self.light.dim(self.level)

    def undo(self) -> None:
        if self._prev_level is not None:
            self.light.dim(self._prev_level)

class SetThermostatCommand(Command):
    def __init__(self, thermostat: Thermostat, temperature: float):
        self.thermostat = thermostat
        self.temperature = temperature
        self._prev_temperature = None

    def execute(self) -> None:
        self._prev_temperature = self.thermostat.temperature
        self.thermostat.set_temperature(self.temperature)

    def undo(self) -> None:
        if self._prev_temperature is not None:
            self.thermostat.set_temperature(self._prev_temperature)

# Invoker 클래스
class SmartHomeController:
    def __init__(self):
        self._command_history: List[Command] = []
        self._current_command = None

    def execute_command(self, command: Command) -> None:
        self._current_command = command
        command.execute()
        self._command_history.append(command)

    def undo_last_command(self) -> None:
        if self._command_history:
            command = self._command_history.pop()
            command.undo()

# 클라이언트 코드
def main():
    # Receiver 객체들 생성
    living_room_light = Light("Living Room")
    bedroom_light = Light("Bedroom")
    living_room_thermostat = Thermostat("Living Room")

    # Command 객체들 생성
    light_on = LightOnCommand(living_room_light)
    bedroom_light_dim = LightDimCommand(bedroom_light, 50)
    set_temp = SetThermostatCommand(living_room_thermostat, 22.5)

    # Invoker 생성 및 커맨드 실행
    controller = SmartHomeController()

    print("=== Executing commands ===")
    controller.execute_command(light_on)
    time.sleep(1)  # 실행 간격을 위한 지연
    controller.execute_command(bedroom_light_dim)
    time.sleep(1)
    controller.execute_command(set_temp)

    print("\n=== Undoing commands ===")
    time.sleep(1)
    controller.undo_last_command()  # 온도 설정 취소
    time.sleep(1)
    controller.undo_last_command()  # 조명 밝기 조절 취소
    time.sleep(1)
    controller.undo_last_command()  # 조명 켜기 취소

if __name__ == "__main__":
    main()

Javascript

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Receiver 클래스들
class Light {
    constructor(location) {
        this.location = location;
        this.isOn = false;
        this.brightness = 0;
    }

    turnOn() {
        this.isOn = true;
        console.log(`${this.location} light is now on`);
    }

    turnOff() {
        this.isOn = false;
        console.log(`${this.location} light is now off`);
    }

    dim(level) {
        this.brightness = level;
        console.log(`${this.location} light dimmed to ${level}%`);
    }
}

class Thermostat {
    constructor(location) {
        this.location = location;
        this.temperature = 20;
    }

    setTemperature(temperature) {
        this.temperature = temperature;
        console.log(`${this.location} thermostat set to ${temperature}°C`);
    }
}

// Command 인터페이스
class Command {
    execute() {
        throw new Error('execute method must be implemented');
    }

    undo() {
        throw new Error('undo method must be implemented');
    }
}

// Concrete Command 클래스들
class LightOnCommand extends Command {
    constructor(light) {
        super();
        this.light = light;
        this._prevState = null;
    }

    execute() {
        this._prevState = this.light.isOn;
        this.light.turnOn();
    }

    undo() {
        if (this._prevState === false) {
            this.light.turnOff();
        }
    }
}

class LightDimCommand extends Command {
    constructor(light, level) {
        super();
        this.light = light;
        this.level = level;
        this._prevLevel = null;
    }

    execute() {
        this._prevLevel = this.light.brightness;
        this.light.dim(this.level);
    }

    undo() {
        if (this._prevLevel !== null) {
            this.light.dim(this._prevLevel);
        }
    }
}

class SetThermostatCommand extends Command {
    constructor(thermostat, temperature) {
        super();
        this.thermostat = thermostat;
        this.temperature = temperature;
        this._prevTemperature = null;
    }

    execute() {
        this._prevTemperature = this.thermostat.temperature;
        this.thermostat.setTemperature(this.temperature);
    }

    undo() {
        if (this._prevTemperature !== null) {
            this.thermostat.setTemperature(this._prevTemperature);
        }
    }
}

// Invoker 클래스
class SmartHomeController {
    constructor() {
        this._commandHistory = [];
        this._currentCommand = null;
    }

    executeCommand(command) {
        this._currentCommand = command;
        command.execute();
        this._commandHistory.push(command);
    }

    undoLastCommand() {
        if (this._commandHistory.length > 0) {
            const command = this._commandHistory.pop();
            command.undo();
        }
    }
}

// 클라이언트 코드
async function main() {
    // Receiver 객체들 생성
    const livingRoomLight = new Light("Living Room");
    const bedroomLight = new Light("Bedroom");
    const livingRoomThermostat = new Thermostat("Living Room");

    // Command 객체들 생성
    const lightOn = new LightOnCommand(livingRoomLight);
    const bedroomLightDim = new LightDimCommand(bedroomLight, 50);
    const setTemp = new SetThermostatCommand(livingRoomThermostat, 22.5);

    // Invoker 생성 및 커맨드 실행
    const controller = new SmartHomeController();

    console.log("=== Executing commands ===");
    controller.executeCommand(lightOn);
    await new Promise(resolve => setTimeout(resolve, 1000));  // 실행 간격을 위한 지연
    controller.executeCommand(bedroomLightDim);
    await new Promise(resolve => setTimeout(resolve, 1000));
    controller.executeCommand(setTemp);

    console.log("\n=== Undoing commands ===");
    await new Promise(resolve => setTimeout(resolve, 1000));
    controller.undoLastCommand();  // 온도 설정 취소
    await new Promise(resolve => setTimeout(resolve, 1000));
    controller.undoLastCommand();  // 조명 밝기 조절 취소
    await new Promise(resolve => setTimeout(resolve, 1000));
    controller.undoLastCommand();  // 조명 켜기 취소
}

main();

용어 정리

용어설명

참고 및 출처


1. 주제의 분류 적절성

Command Pattern(커맨드 패턴) 은 “Computer Science and Engineering > Software Design and Architecture > Software Design Patterns > GoF > Behavioral Design Patterns” 분류에 정확히 부합합니다. GoF(Gang of Four) 에서 정의한 23 가지 디자인 패턴 중 하나로, 대표적인 행동 (Behavioral) 패턴입니다 [1][2][7].


2. 200 자 요약

Command Pattern(커맨드 패턴) 은 요청 (명령) 을 객체로 캡슐화하여, 실행, 취소, 저장, 로깅 등 다양한 방식으로 관리할 수 있게 하는 디자인 패턴입니다. 호출자와 수신자의 결합도를 낮추고, 실행 취소 (Undo), 큐잉, 트랜잭션 등 유연한 기능 확장이 가능합니다 [2][5][20].


3. 250 자 개요

Command Pattern(커맨드 패턴) 은 요청을 객체로 캡슐화해 호출자 (Invoker) 와 수신자 (Receiver) 의 결합도를 낮추고, 명령 실행, 취소, 저장, 재실행 등 다양한 기능을 지원하는 행동 패턴입니다. 각 명령은 독립적인 객체로 관리되어, 실행 이력 관리, 큐잉, 트랜잭션, Undo/Redo 등 복잡한 요구사항을 유연하게 구현할 수 있습니다. 실무에서는 UI 명령 처리, 작업 예약, 트랜잭션 관리 등 다양한 시나리오에 활용됩니다 [2][5][20].


핵심 개념


주요 내용 정리

패턴 이름과 분류

항목내용
패턴 이름Command Pattern (커맨드 패턴)
분류GoF 행동 (Behavioral) 패턴

의도 (Intent)

요청 (명령) 을 객체로 캡슐화하여, 다양한 요청을 파라미터로 전달, 큐잉, 로깅, Undo/Redo 등 다양한 기능을 유연하게 지원하고, 호출자와 수신자의 결합도를 낮춘다 [2][5][15].


다른 이름 (Also Known As)


동기 (Motivation / Forces)


적용 가능성 (Applicability)


구조 및 아키텍처

구조 다이어그램

1
2
3
+---------+       +-----------+       +----------+       +----------+
| Client  | --->  | Invoker   | --->  | Command  | --->  | Receiver |
+---------+       +-----------+       +----------+       +----------+

UML 다이어그램 (예시)

1
[Client] → [Invoker] → [Command] → [Receiver]

구성 요소 및 역할

구성 요소기능 및 역할
Client명령 객체 (Command) 생성 및 설정, Invoker 에 명령 전달
Command명령 실행을 위한 인터페이스, execute() 메서드 정의
ConcreteCommandCommand 인터페이스 구현, Receiver 의 실제 작업 호출
Invoker명령 객체를 실행 (실행, 취소 등), 명령의 실행/취소/저장/재실행 관리
Receiver실제 명령을 수행하는 객체, ConcreteCommand 에서 호출

필수/선택 구성요소

구분구성 요소기능 및 특징
필수Command명령 실행 인터페이스/추상 클래스, execute() 정의
필수ConcreteCommand실제 명령 실행 로직 구현, Receiver 참조
필수Invoker명령 객체 실행 및 관리
필수Receiver실제 작업 수행
선택Undo/Redo 관리명령 실행 이력, 취소/재실행 기능 구현 시 필요
선택Command 큐/로그명령 큐잉, 로그 기록 등 추가 기능 구현 시 필요

주요 원리 및 작동 원리

  1. Client 가 명령 객체 (Command) 를 생성, Invoker 에 전달
  2. Invoker 가 명령 객체의 execute() 호출
  3. ConcreteCommand 가 Receiver 의 실제 작업 메서드 호출
  4. 필요 시, 명령 실행 이력 저장, Undo/Redo, 큐잉 등 추가 기능 구현 가능

작동 원리 다이어그램

1
2
3
4
[Client]
   |
   v
[Invoker] --(execute)--> [Command] --(execute)--> [Receiver]

구현 기법

예시 코드 (Python)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Command 인터페이스
class Command:
    def execute(self):
        pass

# Receiver
class Lamp:
    def turn_on(self):
        print("Lamp is ON")

    def turn_off(self):
        print("Lamp is OFF")

# ConcreteCommand
class LampOnCommand(Command):
    def __init__(self, lamp):
        self.lamp = lamp

    def execute(self):
        self.lamp.turn_on()

class LampOffCommand(Command):
    def __init__(self, lamp):
        self.lamp = lamp

    def execute(self):
        self.lamp.turn_off()

# Invoker
class RemoteControl:
    def set_command(self, command):
        self.command = command

    def press_button(self):
        self.command.execute()

# 사용 예시
lamp = Lamp()
remote = RemoteControl()
remote.set_command(LampOnCommand(lamp))
remote.press_button()  # Lamp is ON
remote.set_command(LampOffCommand(lamp))
remote.press_button()  # Lamp is OFF

장점과 단점

구분항목설명
✅ 장점결합도 감소호출자와 수신자 분리, 유연한 구조
확장성명령 추가/변경이 용이, OCP 준수
Undo/Redo명령 실행 이력 관리 및 취소/재실행 지원
큐잉/로깅명령 저장, 예약 실행, 트랜잭션 등 지원
⚠ 단점클래스 수 증가명령마다 별도 클래스 필요, 복잡성 증가
오버헤드명령 객체 생성 및 관리로 인한 성능 저하 가능
단순 요청엔 과도단순한 작업엔 구조가 과도할 수 있음

도전 과제 및 해결책


분류에 따른 종류 및 유형

분류 기준종류/유형설명
실행 방식단일 명령 (Single)하나의 명령만 실행
매크로 (Macro)여러 명령을 묶어 순차 실행
취소 지원Undo/Redo 지원실행 취소/재실행 기능 포함
실행 시점즉시 실행 (Immediate)명령 즉시 실행
지연 실행 (Deferred)명령 큐잉/예약 실행

실무 적용 예시

분야적용 예시설명
UI/UX버튼/메뉴 명령 처리버튼 클릭 시 명령 객체 실행
자동화/매크로매크로 명령 실행여러 작업을 묶어 일괄 실행
트랜잭션트랜잭션 관리여러 명령을 하나의 트랜잭션으로 처리
Undo/Redo실행 취소/재실행작업 이력 저장 및 복원
작업 예약명령 큐잉/예약 실행명령을 큐에 저장, 예약 실행

활용 사례 (시나리오 기반)

상황 가정: 스마트홈 리모컨 시스템

1
[Client] → [RemoteControl] → [LampOnCommand] → [Lamp]

실무에서 효과적으로 적용하기 위한 고려사항 및 주의점

항목설명권장사항
명령 클래스 관리명령이 많아지면 클래스 수 증가공통 명령 통합, 팩토리 패턴 활용
Undo/Redo 구현명령 이력 관리 필요명령 실행 이력 큐/스택 관리, 메모리 관리
명령 큐잉/예약 실행큐/스케줄러 관리 필요큐/스케줄러 최적화, 우선순위 관리
역할 분리Invoker/Receiver/Command 명확히 분리각 역할의 책임 명확화, SRP 준수

최적화하기 위한 고려사항 및 주의점

항목설명권장사항
명령 큐/이력 최적화큐/이력 관리로 인한 메모리/성능 저하 가능필요 없는 명령 최소화, 이력 관리 최적화
비동기 처리대량 명령 처리 시 블로킹 위험비동기/병렬 처리 도입, 작업 분산
명령 객체 재사용명령 객체 생성 비용 증가명령 객체 풀링, 재사용 전략 적용
로깅/모니터링명령 실행 상태 추적 필요로깅/모니터링 시스템 연동

2025 년 기준 최신 동향

주제항목설명
구현 프레임워크매크로/트랜잭션 명령매크로 명령, 트랜잭션 단위 관리 기능 강화
비동기 처리명령 큐/스케줄러비동기 명령 큐, 예약 실행 기능 확장
클라우드/분산분산 명령 처리마이크로서비스, 서버리스 환경에서 명령 패턴 활용 증가
코드 자동화코드 생성 도구명령 클래스 자동 생성, 관리 도구 발전

주제와 관련하여 주목할 내용

주제항목설명
디자인 원칙SRP, OCP단일 책임, 개방/폐쇄 원칙 실현
Undo/Redo명령 이력 관리실행 취소/재실행 기능 구현에 적합
매크로 명령복합 명령 처리여러 명령 묶어 일괄 실행 가능
비교 패턴전략, 상태 패턴구조적 유사성, 목적 및 사용처 차이 존재

앞으로의 전망

주제항목설명
자동화명령 생성 자동화코드 생성 도구, 템플릿 활용 증가
분산 시스템분산 명령 큐클라우드, 서버리스 환경에서 활용 확대
성능비동기/병렬 명령 처리대규모 트랜잭션, 비동기 명령 처리 연구 활발

하위 주제별 추가 학습 필요 내용

카테고리주제간략 설명
디자인 패턴매크로 명령여러 명령을 묶어 일괄 실행하는 방법
Undo/Redo명령 이력 관리실행 취소/재실행 기능 구현 전략
테스트명령 단위 테스트각 명령별 독립 테스트 전략
성능명령 큐 최적화큐/이력 관리 성능 개선 기법

추가 학습/알아야 할 내용

카테고리주제간략 설명
소프트웨어 아키텍처명령 큐/스케줄러대규모 명령 큐 관리 전략
보안명령 검증/로깅명령 실행 보안, 감사 로그 관리
프레임워크명령 패턴 활용Spring,.NET, Node.js 등 프레임워크별 적용
실무 도구명령 모니터링/관리명령 실행 상태 추적 및 장애 진단 도구

용어 정리

용어설명
Invoker(호출자)명령 객체를 실행하는 역할의 객체
Receiver(수신자)실제 명령을 수행하는 객체
ConcreteCommand실제 명령 실행 로직을 구현한 객체
매크로 명령 (Macro Command)여러 명령을 묶어 일괄 실행하는 명령 객체
큐잉 (Queuing)명령을 큐에 저장해 순차적으로 실행하는 방식
Undo/Redo명령 실행 취소/재실행 기능

참고 및 출처

Citations:
[1] https://www.digitalocean.com/community/tutorials/gangs-of-four-gof-design-patterns
[2] https://coding-study-oj.tistory.com/88
[3] https://jeonyeohun.tistory.com/389
[4] https://chayan-memorias.tistory.com/177
[5] https://mandoooo.tistory.com/114
[6] https://shan0325.tistory.com/28
[7] https://gsbang.tistory.com/entry/Design-Pattern-Command-Pattern%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4
[8] https://sjh9708.tistory.com/135
[9] https://ivans-story.tistory.com/198
[10] https://minttea25.tistory.com/103
[11] https://kchan.tistory.com/5
[12] https://aprofl.pages.dev/dotnet/oop/%EC%84%A4%EA%B3%84/%EB%94%94%EC%9E%90%EC%9D%B8%ED%8C%A8%ED%84%B4/%ED%96%89%EB%8F%99/command/
[13] https://russellstudio.tistory.com/76
[14] https://haeng-on.tistory.com/103
[15] https://keichee.tistory.com/185
[16] https://dfordebugging.wordpress.com/2023/04/29/command-pattern-in-c/
[17] https://velog.io/@bami/%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4-Command-Pattern
[18] https://jgrammer.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4Command-Pattern
[19] https://dingdingmin-back-end-developer.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4-Commend-Pattern-%EA%B0%9C%EB%85%90-%EC%98%88%EC%A0%9C
[20] https://lsoovmee-rhino.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8%ED%8C%A8%ED%84%B4-%ED%96%89%EB%8F%99%ED%8C%A8%ED%84%B48-Command-Pattern-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4
[21] https://vanillacreamdonut.tistory.com/341
[22] https://hellodevelop.tistory.com/33
[23] https://anywayjhwa.tistory.com/11
[24] https://straw961030.tistory.com/358
[25] https://refactoring.guru/design-patterns/command
[26] https://curiousjinan.tistory.com/entry/java-design-pattern-command-pattern-flexible-order-system
[27] https://icksw.tistory.com/251
[28] https://yozm.wishket.com/magazine/detail/2190/
[29] https://refactoring.guru/ko/design-patterns/command
[30] https://jusungpark.tistory.com/18
[31] https://haon.blog/haon/java/command-pattern/
[32] https://ws-pace.tistory.com/184
[33] https://k0102575.github.io/articles/2020-02/command-pattern
[34] http://minsone.github.io/programming/designpattern-command
[35] https://en.wikipedia.org/wiki/Command_pattern
[36] https://python101.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4-Command-Pattern-python-%EC%98%88%EC%A0%9C-%EC%BD%94%EB%93%9C
[37] https://gngsn.tistory.com/136
[38] https://imprint.tistory.com/76
[39] https://mojing.tistory.com/entry/CSDesign-Pattern-GoF-%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%A0%95%EB%A6%AC
[40] https://mojing.tistory.com/entry/CSDesign-Pattern-GoF-%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%ED%96%89%EC%9C%84-%ED%8C%A8%ED%84%B4Behavioral-Pattern-11%EA%B0%80%EC%A7%80-%EC%A0%95%EB%A6%AC
[41] https://gmlwjd9405.github.io/2018/07/07/command-pattern.html
[42] https://blogshine.tistory.com/10
[43] https://studyandwrite.tistory.com/576
[44] https://velog.io/@wlsrhkd4023/%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4Command-Pattern
[45] https://bttrthn-ystrdy.tistory.com/134
[46] https://yuni-q.github.io/design%20pattern/command-pattern/
[47] https://velog.io/@jinmin2216/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4-Command-Pattern
[48] https://velog.io/@ljo_0920/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4
[49] https://velog.io/@chrishan/command
[50] https://wikidocs.net/581
[51] https://coding-by-head.tistory.com/archive/20250102?page=1
[52] https://velog.io/@hyungyugod/Design-Pattern-%EC%9A%94%EC%95%BD-il5qthd7
[53] https://www.udemy.com/course/2025-1-w/
[54] https://ettrends.etri.re.kr/ettrends/213/0905213007/
[55] https://en.dongguk.edu/resources/files/curriculum/2024/10.ai_convergence.pdf
[56] https://nia.or.kr/common/board/Download.do?bcIdx=27995&cbIdx=66361&fileNo=2
[57] https://doohyun.tistory.com/91
[58] https://soojong.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8%ED%8C%A8%ED%84%B4-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4Command-Pattern
[59] https://patterns-dev-kr.github.io/design-patterns/command-pattern/
[60] https://velog.io/@cham/Design-Pattern-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4-Command-Pattern
[61] https://www.businesspost.co.kr/BP?command=article_view&num=395786
[62] https://velog.io/@shasha/%ED%97%A4%EB%93%9C%ED%8D%BC%EC%8A%A4%ED%8A%B8-%EB%94%94%EC%9E%90%EC%9D%B8%ED%8C%A8%ED%84%B4-Chapter-06-%EC%BB%A4%EB%A7%A8%EB%93%9C-%ED%8C%A8%ED%84%B4
[63] https://boycoding.tistory.com/105
[64] https://kingchan223.tistory.com/309
[65] https://coding-start.tistory.com/249
[66] https://velog.io/@ksykma/%EC%BB%A4%EB%A7%A8%EB%93%9CCommand-%ED%8C%A8%ED%84%B4
[67] https://hwan1402.tistory.com/14
[68] https://springframework.guru/gang-of-four-design-patterns/
[69] https://en.wikipedia.org/wiki/Design_Patterns
[70] https://refactoring.guru/design-patterns/behavioral-patterns
[71] https://outliers.tistory.com/entry/%EB%94%94%EC%9E%90%EC%9D%B8-%ED%8C%A8%ED%84%B4Design-Pattern-Command-Pattern
[72] https://amaran-th.github.io/%EC%86%8C%ED%94%84%ED%8A%B8%EC%9B%A8%EC%96%B4%20%EC%84%A4%EA%B3%84/%5B%EB%94%94%EC%9E%90%EC%9D%B8%20%ED%8C%A8%ED%84%B4%5D%20Command%20Pattern(%EB%AA%85%EB%A0%B9%20%ED%8C%A8%ED%84%B4)/
[73] https://hongjinhyeon.tistory.com/49
[74] https://risehyun.tistory.com/26
[75] https://blog.naver.com/jwyoon25/222000521164
[76] https://jkimst.org/upload/pdf/KIMST-2024-27-6-772.pdf
[77] https://www.secui.com/data/upload/trends/1741762700.sHLOk.pdf
[78] https://blog.naver.com/funraon/223745931760
[79] https://apidog.com/kr/blog/top-10-mcp-servers-kr/
[80] https://www.secui.com/data/upload/trends/1741762425.OBtEY.pdf


Perplexity 로부터의 답변: pplx.ai/share

  1. 주제의 분류 적절성
    Command Pattern 은 GoF(Gang of Four) 디자인 패턴 중 **Behavioral Design Pattern (행동 패턴)**에 속합니다.
    따라서 분류 체계인
    **“Computer Science and Engineering” > “Software Design and Architecture” > “Software Design Patterns” > “GoF” > “Behavioral Design Patterns”**는 완벽하게 적절합니다.

  1. 200 자 요약 문장
    Command 패턴은 실행될 기능을 객체로 캡슐화하여 호출자 (Invoker) 와 수신자 (Receiver) 간의 결합을 줄이고, 요청의 큐잉, 로깅, 실행 취소 등을 유연하게 처리할 수 있게 해주는 행동 패턴입니다.

  1. 250 자 개요
    Command 패턴은 요청을 객체로 캡슐화하여 다양한 사용자 행동을 일관된 방식으로 처리할 수 있게 하는 GoF 행동 패턴입니다. 이 패턴은 실행할 기능, 명령, 작업 등을 독립적인 객체로 표현하여, 호출자와 수신자의 결합을 제거하며, 실행 취소 (Undo), 재실행 (Redo), 요청 기록 등의 기능 구현을 용이하게 만듭니다. GUI, 매크로 시스템, 큐 기반 시스템 등에 자주 활용됩니다.

  1. 핵심 개념 (Core Concepts)
항목설명
정의실행할 요청을 객체로 캡슐화하여 다양한 요청, 큐잉, 로깅, 실행 취소 등을 지원하는 패턴
배경명령의 실행 요청자 (Invoker) 와 실제 수행자 (Receiver) 간의 결합을 제거하고, 요청을 객체화하여 동적으로 처리 흐름을 제어
목적요청을 객체로 분리하여 호출자와 수신자 간의 결합도 최소화, 명령 추상화, 실행 이력 관리
필요성명령의 실행을 나중으로 미루거나 저장하거나, 재실행, 취소 등이 필요한 시스템
주요 기능명령 캡슐화, 실행/취소 관리, 요청 로깅, 명령 재사용
특징느슨한 결합 구조, 높은 유연성, Undo/Redo 기능 구현에 적합
원칙OCP(개방 - 폐쇄 원칙), SRP(단일 책임 원칙) 를 잘 준수
작동 원리클라이언트가 명령 객체를 생성 → 호출자 (Invoker) 는 명령 객체를 보관 및 실행 → 명령 객체는 수신자 (Receiver) 에게 작업을 위임

이어서 5 번부터 전체 내용을 구조, 다이어그램, 코드 예제, 실무 적용 예시, 성능 최적화 항목 등으로 상세히 정리해드리겠습니다.

Command Pattern - 개발개발

Command 패턴은 요청을 객체로 캡슐화하여 실행자와 수신자 간의 결합도를 낮추고, 명령의 큐잉, 로깅, 실행 취소 등을 유연하게 처리할 수 있게 해주는 행동 디자인 패턴입니다.


5. 주요 원리 및 작동 원리

UML 클래스 다이어그램

Command Pattern UML Diagram

이 다이어그램은 Command 패턴의 구조를 보여줍니다.

작동 원리 설명

  1. Client: 명령 객체 (ConcreteCommand) 를 생성하고, 수신자 (Receiver) 를 설정합니다.

  2. Invoker: 명령을 저장하고 실행하는 역할을 합니다.

  3. Command: 실행될 명령에 대한 인터페이스를 정의합니다.

  4. ConcreteCommand: Command 인터페이스를 구현하며, 수신자에 대한 참조를 가지고 실제 명령을 실행합니다.

  5. Receiver: 실제 작업을 수행하는 객체로, 명령에 따라 특정 동작을 실행합니다.(개발개발)


6. 구조 및 아키텍처

구성 요소

필수 구성 요소

구성 요소기능 및 역할
Command실행될 명령에 대한 인터페이스를 정의합니다.
ConcreteCommandCommand 인터페이스를 구현하며, 수신자에 대한 참조를 가지고 실제 명령을 실행합니다.
Receiver실제 작업을 수행하는 객체로, 명령에 따라 특정 동작을 실행합니다.
Invoker명령을 저장하고 실행하는 역할을 합니다.
Client명령 객체를 생성하고, 수신자와 연결하여 Invoker 에 전달합니다.

선택 구성 요소

구성 요소기능 및 역할
Undo 기능명령 실행을 취소할 수 있는 기능을 제공합니다.
MacroCommand여러 명령을 하나의 명령으로 묶어 실행할 수 있는 기능을 제공합니다.

7. 구현 기법

정의 및 구성

목적

실제 예시

시스템 구성: 스마트 홈 시스템에서 조명, 오디오 등의 장치를 제어하는 리모컨 (개발개발)

시나리오:

  1. Client 는 조명을 켜는 명령 (LightOnCommand) 을 생성하고, 수신자 (Light 객체) 를 설정합니다.

  2. Invoker(RemoteControl) 는 명령을 저장하고, 버튼이 눌리면 execute() 메서드를 호출하여 명령을 실행합니다.

  3. ConcreteCommand 는 수신자의 on() 메서드를 호출하여 조명을 켭니다.(개발개발)


8. 장점과 단점

구분항목설명
✅ 장점결합도 감소요청을 실행하는 객체와 요청을 발행하는 객체 간의 결합도를 낮춥니다.
명령 큐잉 및 로깅명령을 큐에 저장하거나 로그로 기록할 수 있습니다.
실행 취소 및 재실행명령의 실행 취소 (Undo) 및 재실행 (Redo) 기능을 구현할 수 있습니다.
⚠ 단점클래스 수 증가각 명령마다 별도의 클래스가 필요하여 클래스 수가 증가할 수 있습니다.
복잡성 증가명령이 많아질수록 시스템의 복잡성이 증가할 수 있습니다.

9. 도전 과제


10. 분류에 따른 종류 및 유형

유형설명
Simple Command단일 작업을 수행하는 명령
Macro Command여러 명령을 하나로 묶어 실행하는 명령
Undoable Command실행 취소 기능을 지원하는 명령

11. 실무 적용 예시

분야적용 예시
GUI 애플리케이션버튼 클릭, 메뉴 선택 등의 사용자 인터페이스 이벤트 처리
스마트 홈 시스템장치 제어 명령 (조명 켜기/끄기, 온도 조절 등)
게임 개발플레이어의 행동 (이동, 공격 등) 을 명령으로 처리

12. 활용 사례

상황: 스마트 홈 시스템에서 다양한 장치를 제어하는 리모컨 구현 (개발개발)

시스템 구성:

Workflow:

  1. 사용자가 리모컨의 버튼을 누릅니다.

  2. Invoker 는 해당 버튼에 매핑된 Command 의 execute() 메서드를 호출합니다.

  3. Command 는 Receiver 의 메서드를 호출하여 실제 작업을 수행합니다.


13. 실무에서 효과적으로 적용하기 위한 고려사항 및 주의할 점

고려사항설명권장사항
명령 클래스 관리명령 클래스 수가 많아질 수 있으므로 체계적인 관리가 필요합니다.명령 팩토리 패턴을 도입하여 클래스 생성을 관리합니다.
Undo 기능 구현실행 취소 기능을 구현하려면 명령의 상태를 저장해야 합니다.명령 객체에 이전 상태를 저장하거나 Memento 패턴을 활용합니다.

14. 성능을 최적화하기 위한 고려사항 및 주의할 점

고려사항설명권장사항
명령 큐의 크기 관리명령 큐가 너무 커지면 메모리 사용량이 증가할 수 있습니다.큐의 크기를 제한하거나 오래된 명령을 제거하는 정책을 도입합니다.
명령 실행 시간명령 실행 시간이 길어지면 시스템 응답성이 저하될 수 있습니다.명령 실행을 비동기적으로 처리하거나, 실행 시간을 최적화합니다.

용어 정리

용어설명
Command실행될 명령에 대한 인터페이스를 정의합니다.
ConcreteCommandCommand 인터페이스를 구현하며, 수신자에 대한 참조를 가지고 실제 명령을 실행합니다.
Receiver실제 작업을 수행하는 객체로, 명령에 따라 특정 동작을 실행합니다.
Invoker명령을 저장하고 실행하는 역할을 합니다.
Client명령 객체를 생성하고, 수신자와 연결하여 Invoker 에 전달합니다.

참고 및 출처

물론입니다. 아래는 Command 패턴에 대한 " 참고 및 출처 " 의 계속된 정리입니다.


참고 및 출처


위 자료들은 Command 패턴의 개념적 이해부터 실무 적용까지 전반적인 학습을 위한 신뢰성 있는 참고문헌들입니다.
이후 Command 패턴의 다른 디자인 패턴과의 비교, 예: Strategy, Observer, Mediator 등과의 차이점이 필요하다면 추가로 제공드릴 수 있습니다. 원하시면 다음 주제로 이어가겠습니다.

Command Pattern 패턴 분석 보고서

1. 분류 검증 및 요약

분류 검증: “Computer Science and Engineering” > “Software Design and Architecture” > “Software Design Patterns” > “GoF” > “Behavioral Design Patterns” 이 분류는 적절합니다. Command Pattern 은 Gang of Four (GoF) 에서 정의한 23 개 설계 패턴 중 하나이며, 객체들 간의 상호작용과 요청 처리 방식을 다루는 행동 패턴 (Behavioral Pattern) 입니다.

200 자 요약: Command Pattern(명령 패턴) 은 요청을 객체로 캡슐화하여 요청자와 수신자를 분리하는 행동 패턴입니다. 요청의 매개변수화, 큐잉, 로깅, 실행 취소/재실행 기능을 지원하며, GUI 애플리케이션, 매크로 명령, 트랜잭션 처리 등에서 널리 활용됩니다.

250 자 개요: Command Pattern 은 메소드 호출을 객체로 변환하여 호출자와 수신자 간의 결합도를 낮추는 패턴입니다. 각 명령은 실행에 필요한 모든 정보를 포함한 독립적인 객체가 되어, 명령의 저장, 전달, 실행 지연이 가능합니다. 특히 GUI 애플리케이션의 버튼 - 액션 분리, 매크로 기능, Undo/Redo 시스템, 원격 프로시저 호출, 마이크로서비스의 CQRS 패턴 등에서 핵심적인 역할을 수행합니다.


2. 핵심 개념

Command Pattern 의 핵심 개념들:


3. 상세 분석

3.1 배경 및 목적

배경: 전통적인 객체지향 프로그래밍에서 메소드 호출은 컴파일 시점에 고정되며, 호출자는 수신자를 직접적으로 알아야 합니다. 이는 GUI 애플리케이션에서 버튼과 액션 간의 강한 결합, 실행 취소 기능 구현의 어려움, 명령의 재사용 제약 등의 문제를 야기합니다.

목적 및 필요성:

3.2 구조 및 아키텍처

필수 구성요소:

  1. Command (명령 인터페이스)

    • 기능: 명령 실행을 위한 공통 인터페이스 정의
    • 역할: execute() 메소드를 통한 명령 실행 계약
    • 특징: 모든 구체적 명령이 구현해야 하는 표준 인터페이스
  2. ConcreteCommand (구체적 명령)

    • 기능: 특정 작업을 수행하는 명령의 구현
    • 역할: Receiver 객체와 액션을 바인딩하고 execute() 메소드 구현
    • 특징: 명령 실행에 필요한 모든 정보와 상태 포함
  3. Receiver (수신자)

    • 기능: 실제 작업을 수행하는 객체
    • 역할: 비즈니스 로직과 실제 작업 처리
    • 특징: Command 객체에 의해 호출되는 구체적인 작업 메소드 보유
  4. Invoker (호출자)

    • 기능: 명령을 실행하는 객체
    • 역할: 명령 객체를 저장하고 적절한 시점에 실행
    • 특징: 구체적인 명령에 대한 지식 없이 명령 실행

선택 구성요소:

  1. Client (클라이언트)

    • 기능: ConcreteCommand 객체 생성 및 Receiver 설정
    • 역할: 명령 체인 구성 및 초기화
    • 특징: 전체 명령 구조를 조립하는 역할
  2. MacroCommand (매크로 명령)

    • 기능: 여러 명령을 하나로 묶어 순차 실행
    • 역할: 복합 작업의 단일 명령화
    • 특징: Composite 패턴과 결합하여 구현

3.3 주요 원리 및 작동 원리

sequenceDiagram
    participant Client
    participant Invoker
    participant ConcreteCommand
    participant Receiver
    
    Client->>ConcreteCommand: new ConcreteCommand(receiver)
    Client->>Invoker: setCommand(command)
    Client->>Invoker: executeCommand()
    Invoker->>ConcreteCommand: execute()
    ConcreteCommand->>Receiver: action()
    Receiver-->>ConcreteCommand: result
    ConcreteCommand-->>Invoker: completed
    Invoker-->>Client: done

작동 원리:

  1. 클라이언트가 ConcreteCommand 객체를 생성하고 Receiver 설정
  2. Invoker 에 명령 객체 등록
  3. Invoker 가 명령의 execute() 메소드 호출
  4. ConcreteCommand 가 Receiver 의 적절한 메소드 호출
  5. 결과를 클라이언트에게 반환

3.4 구현 기법

3.4.1 기본 구현 기법

3.4.2 함수형 구현 기법

3.4.3 애노테이션 기반 구현

3.4.4 비동기 명령 구현

3.5 장점과 단점

구분항목설명
✅ 장점결합도 감소호출자와 수신자 간의 직접적인 의존성 제거
매개변수화다양한 요청으로 객체를 매개변수화 가능
실행 취소 지원명령의 역방향 실행을 통한 Undo/Redo 기능
로깅 및 큐잉명령의 기록 보관 및 대기열 처리
매크로 명령여러 명령을 조합한 복합 작업 구성
확장성새로운 명령 추가 시 기존 코드 수정 불필요
⚠ 단점복잡성 증가단순한 작업에 대한 과도한 추상화
클래스 수 증가각 명령마다 별도 클래스 필요
메모리 오버헤드명령 객체 생성 및 저장으로 인한 메모리 사용
간접 호출 비용직접 메소드 호출 대비 성능 오버헤드
디버깅 복잡성명령 체인 추적의 어려움

3.6 도전 과제 및 해결책

도전 과제 1: 성능 최적화

도전 과제 2: 메모리 관리

도전 과제 3: 복잡한 실행 취소

3.7 분류에 따른 종류 및 유형

분류 기준유형설명특징
실행 방식Synchronous Command동기적 명령 실행즉시 결과 반환, 단순한 구조
Asynchronous Command비동기적 명령 실행지연 실행, 콜백 또는 Future 사용
상태 관리Stateless Command상태를 갖지 않는 명령재사용 가능, 스레드 안전
Stateful Command상태를 포함하는 명령실행 컨텍스트 보존, 실행 취소 지원
실행 취소Undoable Command실행 취소 가능한 명령undo() 메소드 구현
Non-Undoable Command실행 취소 불가능한 명령단방향 작업, 부작용 존재
조합 방식Simple Command단일 작업 명령하나의 액션만 수행
Composite Command복합 명령 (매크로)여러 명령의 조합, Composite 패턴 적용

3.8 실무 적용 예시

도메인적용 사례명령 예시장점
GUI 애플리케이션메뉴/툴바 시스템SaveCommand, CopyCommand, PasteCommand동적 메뉴 구성, 키보드 단축키 지원
텍스트 에디터편집 작업InsertTextCommand, DeleteTextCommand무제한 Undo/Redo, 매크로 기록
데이터베이스트랜잭션 처리InsertCommand, UpdateCommand, DeleteCommand롤백 지원, 배치 처리
네트워크 통신원격 프로시저 호출HTTPCommand, RPCCommand재시도 로직, 요청 큐잉
게임 개발플레이어 액션MoveCommand, AttackCommand, SkillCommand리플레이 시스템, AI 명령 처리
IoT 시스템디바이스 제어TurnOnCommand, SetTemperatureCommand원격 제어, 스케줄링

3.9 활용 사례: 스마트 홈 자동화 시스템

시나리오: IoT 기반 스마트 홈에서 다양한 디바이스를 통합 제어하고 자동화 시나리오를 실행하는 시스템

시스템 구성:

graph TB
    A[스마트폰 앱] --> B[IoT Gateway]
    B --> C[Command Processor]
    C --> D[Light Controller]
    C --> E[HVAC Controller]
    C --> F[Security Controller]
    D --> G[LED 조명]
    E --> H[에어컨]
    F --> I[보안 카메라]

Workflow:

  1. 명령 생성 단계: 사용자가 스마트폰 앱에서 " 집에 도착 " 시나리오 실행
  2. 명령 조합 단계: MacroCommand 가 여러 개별 명령들을 조합
    • TurnOnLightsCommand: 현관, 거실 조명 켜기
    • SetTemperatureCommand: 에어컨 온도 22 도 설정
    • DisarmSecurityCommand: 보안 시스템 해제
  3. 명령 전송 단계: IoT Gateway 를 통해 각 디바이스에 명령 전달
  4. 실행 및 피드백: 각 컨트롤러가 명령 실행 후 상태 피드백
  5. 로깅 및 히스토리: 모든 명령 실행 내역을 로그로 기록

Command Pattern 의 역할:

3.10 실무 고려사항 및 주의점

구분고려사항설명권장사항
설계명령 세분화 수준너무 세밀하면 복잡성 증가, 너무 크면 재사용성 저하비즈니스 로직 단위로 명령 정의
매개변수 관리명령 실행에 필요한 매개변수 전달 방식생성자 주입 또는 빌더 패턴 활용
예외 처리명령 실행 중 발생하는 예외 관리 전략체크 예외를 언체크 예외로 래핑
구현스레드 안전성멀티스레드 환경에서의 명령 객체 공유불변 객체 설계, 스레드 로컬 사용
메모리 최적화대량의 명령 객체 생성 시 메모리 관리객체 풀링, 플라이웨이트 패턴 적용
실행 취소 구현복잡한 상태 변경에 대한 실행 취소 로직Memento 패턴, 보상 트랜잭션 활용

3.11 성능 최적화 고려사항

구분최적화 기법설명권장사항
객체 생성명령 풀링자주 사용되는 명령 객체의 재사용Apache Commons Pool 활용
프로토타입 패턴명령 객체의 복제를 통한 생성 비용 절약얕은 복사와 깊은 복사 구분
실행 성능비동기 처리I/O 집약적 명령의 비동기 실행CompletableFuture, Reactor 활용
배치 처리유사한 명령들의 일괄 처리배치 크기 최적화, 벌크 연산
메모리 관리지연 로딩필요 시점에만 무거운 리소스 로딩Lazy Initialization 패턴
히스토리 제한Undo 스택 크기 제한으로 메모리 사용량 제어LRU 기반 히스토리 관리

4. GoF 패턴 상세 정보

4.1 패턴 이름과 분류

4.2 의도 (Intent)

요청을 객체로 캡슐화하여 다양한 요청으로 클라이언트를 매개변수화하고, 요청을 큐에 저장하거나 로그를 남기며, 실행 취소 가능한 연산을 지원합니다.

4.3 다른 이름 (Also Known As)

4.4 동기 (Motivation / Forces)

4.5 적용 가능성 (Applicability)

4.6 참여자 (Participants)

  1. Command: 연산 수행에 필요한 인터페이스 선언
  2. ConcreteCommand: Receiver 객체와 액션 간의 연결을 정의하고 execute() 구현
  3. Client: ConcreteCommand 객체를 생성하고 Receiver 설정
  4. Invoker: 명령에게 처리를 요청
  5. Receiver: 요청에 관련된 연산 수행 방법을 알고 있는 객체

4.7 협력 (Collaboration)

4.8 결과 (Consequences)

장점:

단점:

4.9 구현 (Implementation)

구현 시 고려사항:

4.10 샘플 코드 (Sample Code)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// Command 인터페이스
public interface Command {
    void execute();
    void undo(); // 실행 취소를 위한 메소드
}

// 구체적인 명령 클래스들
public class LightOnCommand implements Command {
    private Light light;
    
    public LightOnCommand(Light light) {
        this.light = light;
    }
    
    @Override
    public void execute() {
        light.on();
    }
    
    @Override
    public void undo() {
        light.off();
    }
}

public class LightOffCommand implements Command {
    private Light light;
    
    public LightOffCommand(Light light) {
        this.light = light;
    }
    
    @Override
    public void execute() {
        light.off();
    }
    
    @Override
    public void undo() {
        light.on();
    }
}

// Receiver 클래스
public class Light {
    private boolean isOn = false;
    
    public void on() {
        isOn = true;
        System.out.println("Light is ON");
    }
    
    public void off() {
        isOn = false;
        System.out.println("Light is OFF");
    }
}

// Invoker 클래스
public class RemoteControl {
    private Command[] onCommands;
    private Command[] offCommands;
    private Command undoCommand;
    
    public RemoteControl() {
        onCommands = new Command[7];
        offCommands = new Command[7];
        
        Command noCommand = new NoCommand();
        for (int i = 0; i < 7; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        undoCommand = noCommand;
    }
    
    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }
    
    public void onButtonPressed(int slot) {
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }
    
    public void offButtonPressed(int slot) {
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }
    
    public void undoButtonPressed() {
        undoCommand.undo();
    }
}

// Null Object 패턴을 적용한 기본 명령
public class NoCommand implements Command {
    @Override
    public void execute() {}
    
    @Override
    public void undo() {}
}

// 클라이언트 코드
public class RemoteControlTest {
    public static void main(String[] args) {
        RemoteControl remote = new RemoteControl();
        
        Light livingRoomLight = new Light();
        LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight);
        LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight);
        
        remote.setCommand(0, livingRoomLightOn, livingRoomLightOff);
        
        remote.onButtonPressed(0);   // Light is ON
        remote.offButtonPressed(0);  // Light is OFF
        remote.undoButtonPressed();  // Light is ON (undo)
    }
}

// 매크로 명령 예시
public class MacroCommand implements Command {
    private Command[] commands;
    
    public MacroCommand(Command[] commands) {
        this.commands = commands;
    }
    
    @Override
    public void execute() {
        for (Command command : commands) {
            command.execute();
        }
    }
    
    @Override
    public void undo() {
        // 역순으로 실행 취소
        for (int i = commands.length - 1; i >= 0; i--) {
            commands[i].undo();
        }
    }
}

4.11 알려진 사용 (Known Uses)


5. 2025 년 기준 최신 동향

주제항목설명
마이크로서비스CQRS 패턴 통합Command Pattern 이 CQRS(Command Query Responsibility Segregation) 의 핵심으로 활용
클라우드 네이티브서버리스 명령 처리AWS Lambda, Azure Functions 를 활용한 이벤트 기반 명령 실행
이벤트 소싱불변 명령 로그모든 상태 변경을 명령 이벤트로 저장하는 Event Sourcing 과 결합
AI/ML 통합지능형 명령 최적화AI 를 활용한 명령 실행 순서 최적화 및 예측적 명령 처리
분산 시스템분산 명령 처리Saga 패턴과 결합한 분산 트랜잭션 처리
실시간 처리스트리밍 명령Apache Kafka, Redis Streams 를 활용한 실시간 명령 스트리밍

6. 주목할 내용

주제항목설명
함수형 프로그래밍함수형 명령고차 함수와 커링을 활용한 함수형 Command Pattern 구현
리액티브 프로그래밍리액티브 명령RxJava, Project Reactor 를 활용한 비동기 명령 체인
블록체인스마트 컨트랙트 명령블록체인 기반 불변 명령 실행 및 검증
GraphQL리졸버 명령GraphQL 스키마 실행을 위한 명령 패턴 활용
컨테이너 오케스트레이션쿠버네티스 명령kubectl 명령을 통한 선언적 인프라 관리
메타버스/XR제스처 명령VR/AR 환경에서의 제스처 기반 명령 인식 및 처리

7. 앞으로의 전망

주제항목설명
양자 컴퓨팅양자 명령 게이트양자 게이트를 명령 객체로 추상화한 양자 알고리즘 구현
엣지 컴퓨팅분산 명령 실행IoT 디바이스에서의 로컬 명령 처리 및 클라우드 동기화
자율 시스템자율 명령 생성AI 시스템이 자동으로 명령을 생성하고 실행하는 자율 운영
신경 인터페이스뇌 - 컴퓨터 명령뇌 신호를 직접 명령으로 변환하는 BCI(Brain-Computer Interface)
디지털 트윈가상 - 물리 명령 동기화디지털 트윈과 실제 시스템 간의 실시간 명령 동기화
Web3탈중앙화 명령 실행블록체인 기반 분산 명령 실행 및 합의 메커니즘

8. 추가 학습 내용 (하위 주제)

카테고리주제설명
고급 구현Functional Command Pattern함수형 패러다임을 활용한 명령 패턴 구현 기법
성능 최적화Command Pooling & Caching명령 객체의 풀링과 캐싱을 통한 성능 향상
아키텍처 패턴CQRS Architecture명령 - 쿼리 분리 아키텍처 설계 및 구현
분산 시스템Distributed Command Processing분산 환경에서의 명령 처리 및 동기화
테스팅Command Pattern Testing명령 패턴의 효과적인 단위 테스트 및 모킹 기법
보안Secure Command Execution명령 실행의 보안 검증 및 권한 관리

9. 관련 학습 내용

관련 분야주제설명
이벤트 기반 아키텍처Event Sourcing이벤트 스토어를 통한 상태 관리 및 명령 이력 추적
함수형 프로그래밍Monad Pattern함수형 언어에서의 명령 체이닝 및 에러 처리
분산 시스템Saga Pattern분산 트랜잭션 처리를 위한 명령 조정 패턴
데이터베이스Database Command Pattern데이터베이스 연산의 명령 객체화 및 트랜잭션 관리
웹 개발API Command PatternRESTful API 설계에서의 명령 패턴 활용
게임 개발Game Command System게임 로직에서의 명령 처리 및 리플레이 시스템
모바일 개발Mobile Command Architecture모바일 앱에서의 명령 기반 아키텍처 설계

용어 정리

용어설명
호출자 (Invoker)명령을 실행하는 객체로, 구체적인 명령 내용을 몰라도 실행 가능
수신자 (Receiver)실제 작업을 수행하는 객체로, 비즈니스 로직을 포함
매크로 명령 (Macro Command)여러 개의 명령을 하나로 묶어서 순차적으로 실행하는 복합 명령
실행 취소 (Undo)이전에 실행된 명령의 효과를 되돌리는 기능
재실행 (Redo)실행 취소된 명령을 다시 실행하는 기능
큐잉 (Queuing)명령을 대기열에 저장하여 순차적으로 처리하는 방식
매개변수화 (Parameterization)다양한 명령으로 객체를 구성할 수 있게 하는 기능
지연 실행 (Deferred Execution)명령 생성 시점과 실행 시점을 분리하여 필요할 때 실행
보상 명령 (Compensating Command)원본 명령의 효과를 상쇄하는 역방향 명령
명령 로그 (Command Log)실행된 명령들의 기록을 저장하는 시스템

참고 및 출처