Command Method

Command Method

Command Method

Command methods are a type of behavioural design pattern that encapsulates a request as an object. This type of pattern helps in promoting the invocation of a method on an object to full object status and also encapsulates all the information needed to perform an action or trigger an event.

Implementation

class Command:
    def execute(self):
        pass

class SimpleCommand(Command):
    def __init__(self, payload):
        self._payload = payload
    def execute(self):
        print("Simple Command: See,I can do simple things like printing {}".format(self._payload))

class ComplexCommand(Command):
    def __init__(self, receiver, a, b):
        self._receiver = receiver
        self._a = a
        self._b = b
    def execute(self):
        print("Complex Command: Complex stuff should be done by a receiver object")
        self._receiver.do_something(self._a)
        self._receiver.do_something_else(self._b)

class Receiver:
    def do_something(self, a):
        print("\nRecevier: Working on ({}.)".format(a))
    def do_something_else(self, b):
        print("\nReceiver: Also Working on ({}.)".format(b))

class Invoker:
    _on_start = None
    _on_finish = None
    def set_on_start(self, command):
        self._on_start = command
    def set_on_finish(self, command):
        self._on_finish = command
    def do_something_important(self):
        print("Invoker: Does anybody want something done before I begin?")
        if isinstance(self._on_start, Command):
            self._on_start.execute()
        print("Invoker Does anybody want something really important...")
        print("Invoker Does anybody want something done after I finish ?")
        if isinstance(self._on_finish, Command):
            self._on_finish.execute()

if __name__ == '__main__':
    invoker = Invoker()
    invoker.set_on_start(SimpleCommand("Python For Cybersecurity"))
    receiver = Receiver()
    invoker.set_on_start(ComplexCommand(receiver, "Sending Mail", "Save report"))
    invoker.do_something_important()
The program above generates the following output −
ProBook:~/Desktop/$ python command.py
Invoker: Does anybody want something done before I begin?
Complex Command: Complex stuff should be done by a receiver object

Recevier: Working on (Send Mail.)

Receiver: Also Working on (Save report.)
Invoker Does anybody want something really important...
Invoker Does anybody want something done after I finish ?

The output implements the keywords listed in Python language and all the commands.

Pros and Cons

Pros
  • Single Responsibility Principle
  • Open/Closed Principle
Cons
  • The code from the user may become more complicated since you’re introducing a whole new layer between senders and receivers.
Lesson Content