[python] 커맨드 디자인 패턴
커맨드 디자인 패턴은 객체 지향 프로그래밍에서 많이 사용되는 디자인 패턴 중 하나입니다. 이 패턴은 요청을 객체의 형태로 캡슐화하여 매개 변수화할 수 있고, 요청을 큐에 저장하거나 로그로 기록하고 실행 취소할 수 있게 합니다. 이 패턴은 행위형 패턴으로 분류되며, 요청을 발생시키는 객체와 요청을 수행하는 객체를 분리하여 느슨한 결합을 유지할 수 있도록 돕습니다.
패턴 구성 요소
커맨드 디자인 패턴은 기본적으로 다음과 같은 구성 요소로 구성됩니다:
- 커맨드(Command): 요청을 나타내는 인터페이스입니다. 이 인터페이스는
execute()
메서드를 정의하고, 이 메서드는 요청을 수행하기 위해 필요한 동작을 구현합니다. - 컨크리트 커맨드(Concrete Command):
Command
인터페이스의 구체적인 구현체입니다.execute()
메서드에서 실제 동작을 수행합니다. - 수신자(Receiver):
Command
객체가 요청을 수행하는 데 사용하는 객체입니다. 이 객체는Command
에 대한 호출을 처리합니다. - 호출자(Invoker):
Command
객체를 생성하고 실행하는 객체입니다. 이 객체는Command
객체와 수신자 객체 사이의 관계를 설정합니다.
예제 코드
# 커맨드 인터페이스
class Command:
def execute(self):
pass
# 컨크리트 커맨드 1
class ConcreteCommand1(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action1()
# 컨크리트 커맨드 2
class ConcreteCommand2(Command):
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
self.receiver.action2()
# 수신자
class Receiver:
def action1(self):
print("수신자: Action 1 수행")
def action2(self):
print("수신자: Action 2 수행")
# 호출자
class Invoker:
def __init__(self):
self.commands = []
def add_command(self, command):
self.commands.append(command)
def execute_commands(self):
for command in self.commands:
command.execute()
# 클라이언트 코드
receiver = Receiver()
command1 = ConcreteCommand1(receiver)
command2 = ConcreteCommand2(receiver)
invoker = Invoker()
invoker.add_command(command1)
invoker.add_command(command2)
invoker.execute_commands()