Python Design Patterns Command Pattern

Python Design Patterns: Command Pattern

The Command pattern adds a level of abstraction between actions, including an object that invokes those actions.

In this design pattern, the client creates a command object, which contains a list of commands to be executed. The created command object implements a specific interface.

The following is the basic structure of the Command pattern

Python Design Patterns - Command

How to Implement the Command Pattern

Now we’ll see how to implement this design pattern.

def demo(a,b,c):
print 'a:',a
print 'b:',b
print 'c:',c

class Command:
def __init__(self, cmd, *args):
self._cmd=cmd
self._args=args

def __call__(self, *args):
return apply(self._cmd, self._args+args)
cmd = Command(dir,__builtins__)
print cmd()

cmd = Command(demo,1,2)
cmd(3)

Output

The above program produces the following output –

Python Design Patterns – Commands

Explanation

This output implements all commands and keywords listed in the Python language. It also prints the required values for variables.

Leave a Reply

Your email address will not be published. Required fields are marked *