Skip to content

Instantly share code, notes, and snippets.

@syedjafer
Created May 20, 2021 00:40
Show Gist options
  • Save syedjafer/7c389b49773e8fbc8adae82fa11867b6 to your computer and use it in GitHub Desktop.
Save syedjafer/7c389b49773e8fbc8adae82fa11867b6 to your computer and use it in GitHub Desktop.
# Receiver
class Volume:
def __init__(self, volume=0):
self.volume = volume
def volume_up(self, value=1):
self.volume += value
print(f"Volume is Up - {self.volume}")
def volume_down(self, value=1):
self.volume -= value
print(f"Volume is Down - {self.volume}")
# Invoker
class Remote:
def __init__(self):
self.commands = {}
def register(self, command_name, command):
self.commands[command_name] = command
def execute(self, command_name):
if self.commands.get(command_name):
command = self.commands.get(command_name)
command.execute()
else:
print(f"Command {command_name} is not recognized")
from abc import abstractmethod, ABCMeta
class IVolume(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class VolumeUpCommand(IVolume):
def __init__(self, volume):
self.volume = volume
def execute(self):
self.volume.volume_up()
class VolumeDownCommand(IVolume):
def __init__(self, volume):
self.volume = volume
def execute(self):
self.volume.volume_down()
# Create a receiver
volume = Volume()
# Commands
volume_up_cmd = VolumeUpCommand(volume=volume)
volume_down_cmd = VolumeDownCommand(volume=volume)
# Register the command in Remote(Invoker)
remote = Remote()
remote.register("+", volume_up_cmd)
remote.register("-", volume_down_cmd)
remote.execute("+")
remote.execute("+")
remote.execute("-")
remote.execute("+")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment