The following piece of code (source: en.wikipedia.org, modified) shows the basic components of the command pattern: the client which prepares the command, the invoker which calls the command and the receiver which executes the command:
#!/usr/bin/env python
class Invoker(object):
def __init__(self, flip_up_cmd, flip_down_cmd):
self.flip_up = flip_up_cmd
self.flip_down = flip_down_cmd
class Receiver(object):
def turn_on(self):
print( "The light is on")
def turn_off(self):
print( "The light is off")
class Client(object):
def __init__(self):
receiver = Receiver()
self._invoker = Invoker(receiver.turn_on, receiver.turn_off)
def switch(self, cmd):
cmd = cmd.strip().upper()
if cmd == "ON":
self._invoker.flip_up()
elif cmd == "OFF":
self._invoker.flip_down()
else:
print( 'Argument "ON" or "OFF" is required.')
if __name__ == "__main__":
client = Client()
print( "Switch ON test.")
client.switch("ON")
print( "Switch OFF test.")
client.switch("OFF")
print( "Invalid Command test.")
client.switch("****")