class Light(object):
def on(self):
print('Light on')
def off(self):
print('Light off')
class TV(object):
def on(self):
print('TV open')
def off(self):
print('TV off')
class ICommand(object):
def execute(self):
raise NotImplementedError
class LightOnCommand(ICommand):
def __init__(self, light):
if isinstance(light, type(Light())):
self._Light = light
else:
raise TypeError
def execute(self):
self._Light.on()
class LightOffCommand(ICommand):
def __init__(self, light):
if isinstance(light, type(Light())):
self._Light = light
else:
raise TypeError
def execute(self):
self._Light.off()
class TVOpenCommand(ICommand):
def __init__(self, tv):
if isinstance(tv, type(TV())):
self._TV = tv
else:
raise TypeError
def execute(self):
self._TV.on()
class TVCloseCommand(ICommand):
def __init__(self, tv):
if isinstance(tv, type(TV())):
self._TV = tv
else:
raise TypeError
def execute(self):
self._TV.off()
class SimpleRemoteControl(object):
def __init__(self):
self._on_command = {}
self._off_command = {}
def __str__(self):
print('\nCommond key:')
print("-"*10)
for key in self._on_command.keys():
print(key)
return "-"*10
def set_command(self, name, on_command, off_command):
if isinstance(on_command, type(ICommand())):
self._on_command[name] = on_command
else:
raise TypeError('on command type is error')
if isinstance(off_command, type(ICommand())):
self._off_command[name] = off_command
else:
raise TypeError('off command type is error')
def on_press_bottom(self, name):
if isinstance(self._on_command[name], type(ICommand())):
self._on_command[name].execute()
def off_press_bottom(self, name):
if isinstance(self._off_command[name], type(ICommand())):
self._off_command[name].execute()
def main():
control = SimpleRemoteControl()
light = Light()
tv = TV()
light_on_command = LightOnCommand(light)
light_off_command = LightOffCommand(light)
tv_on_command = TVOpenCommand(tv)
tv_off_command = TVCloseCommand(tv)
control.set_command("Light", light_on_command, light_off_command)
control.on_press_bottom("Light")
control.off_press_bottom("Light")
control.set_command("TV", tv_on_command, tv_off_command)
control.on_press_bottom("TV")
control.off_press_bottom("TV")
print(control)
if __name__ == "__main__":
main()