command pattern
11 Nov 2016 | python patternCommand 요청과 실행을 분리하자!
Command의 요청, 실행을 분리하면서 의존성을 크게 낮춘 모델. command를 abstract class 또는 interface
로 만들고 concrete command
를 구현한다.
Receiver
는 실제 Action을 가지고있는 객체이며 command
는 이를 사용하여 Action을 만든다. Client가 Invoker
에게 command
를 세팅하면 추후에 Invoker
에게 실행을 요청하며 실행된다.
Overview
Code
from abc import ABCMeta, abstractmethod
# Receiver
class Light:
def on(self):
print("Light On")
def off(self):
print("Light Off")
# Command
class Command:
__metaclass__ = ABCMeta
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
# Concrete Command
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.on()
def undo(self):
self.light.off()
# Invoker
class SimpleRemoteControl:
def SetCommand(self, command):
self.slot = command
def ButtonPressed(self):
self.slot.execute()
if __name__ == '__main__':
controller = SimpleRemoteControl()
controller.SetCommand(LightOnCommand(Light()))
controller.ButtonPressed()