본문으로 이동
메뉴 여닫기
환경 설정 메뉴 여닫기
개인 메뉴 여닫기
로그인하지 않음
지금 편집한다면 당신의 IP 주소가 공개될 수 있습니다.

커맨드 패턴(Command Pattern)은 요청을 실행할 수 있는 객체로 캡슐화해, 요청을 보내는 쪽(호출자)과 실제로 처리하는 쪽(수신자)을 분리하는 GoF 행위 패턴이다.

역할 설명
Command 실행 연산 execute() 를 선언한 인터페이스
ConcreteCommand Command 를 구현하고 수신자에 대한 참조를 가진다. execute() 가 불리면 수신자의 연산을 호출한다
Invoker(호출자) Command 객체를 보관했다가 execute() 를 부른다. 어떤 수신자가 무엇을 하는지 모른다
Receiver(수신자) 실제 일을 하는 객체
Client ConcreteCommand 를 만들고 수신자를 연결해 호출자에게 넘긴다

버튼(Invoker)에 setCommand(Command) 로 LightOnCommand(ConcreteCommand)를 넣어 두고, 버튼이 눌리면 command.execute() 가 불려 LightOnCommand 가 가진 램프(Receiver)의 turnOn() 을 호출하는 구조가 전형적인 예이다. 버튼은 램프를 몰라도 되므로 같은 버튼에 다른 명령을 바꿔 끼울 수 있고, 명령 객체를 큐에 쌓거나 기록해 실행 취소(undo)·재실행·매크로를 구현할 수 있다.[1][2]

비슷한 패턴과 구별하기

편집 원본 편집
패턴 핵심 클래스 다이어그램에서 보이는 모습
커맨드 요청을 객체로 만들어 호출자와 수신자를 떼어 낸다 호출자가 execute() 하나뿐인 Command 인터페이스에 의존하고, 구체 명령이 수신자를 필드로 가진다
어댑터 인터페이스가 맞지 않는 기존 클래스를 원하는 인터페이스로 바꾼다 어댑터가 목표 인터페이스를 구현하면서, 연산 이름이나 시그니처가 다른 기존 클래스(Adaptee)를 필드로 두고 호출한다
프록시 실제 객체와 같은 인터페이스의 대리 객체가 접근을 통제한다 프록시와 실제 객체가 같은 인터페이스를 구현한다
전략 같은 일을 하는 알고리즘을 바꿔 끼운다 Context 가 알고리즘 인터페이스를 가지고 구체 전략을 교체한다
  from abc import ABCMeta, abstractmethod
  class Order(metaclass=ABCMeta):
     @abstractmethod
     def execute(self):
         pass
  class BuyStockOrder(Order):
     def __init__(self, stock):
         self.stock = stock
     def execute(self):
         self.stock.buy()
  class SellStockOrder(Order):
     def __init__(self, stock):
         self.stock = stock
     def execute(self):
         self.stock.sell()
  class StockTrade:
     def buy(self):
         print(“You will buy stocks”)
     def sell(self):
         print(“You will sell stocks”)
  class Agent:
     def __init__(self):
         self.__orderQueue = []
     def placeOrder(self, order):
         self.__orderQueue.append(order)
         order.execute()
  if __name__ == ‘__main__’:
     #Client
     stock = StockTrade()
     buyStock = BuyStockOrder(stock)
     sellStock = SellStockOrder(stock)
     #Invoker
     agent = Agent()
     agent.placeOrder(buyStock)
     agent.placeOrder(sellStock)
  1. ↑ Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, 『Design Patterns: Elements of Reusable Object-Oriented Software』, Addison-Wesley, 1994, Command.
  2. ↑ 「Command」, Refactoring.Guru, https://refactoring.guru/design-patterns/command, 확인일: 2026-11-04.