command pattern

|

Command 요청과 실행을 분리하자!

Command의 요청, 실행을 분리하면서 의존성을 크게 낮춘 모델. command를 abstract class 또는 interface로 만들고 concrete command를 구현한다. Receiver는 실제 Action을 가지고있는 객체이며 command는 이를 사용하여 Action을 만든다. Client가 Invoker에게 command를 세팅하면 추후에 Invoker에게 실행을 요청하며 실행된다.

Overview

sequence-100158873-orig.gif

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()