Sunday, April 25, 2010

Python: Command Design Pattern

Hi Guys,

Recently I was working on learning design patterns in python. If you are not reading them , I highly recommend you to do so...they definitely help you in creating better designs or frameworks.

Here's something on Command Design Pattern:

class CommandPattern:
def __init__(self, cmd):
self.cmd = cmd
self._dict = { 'add' : 'add()', 'sub' : 'sub()' }
if self._dict.has_key(cmd):
call = self._dict[cmd]
call = "self." + call
eval(call)
else:
print "Invalid Command...."
def add(self):
print "In Add"
def sub(self):
print "In Sub"
cmdpattern = CommandPattern('add')

Explaination:
Command design pattern is seen as an example of encapsulation.

As per wikipedia, Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.

In the above example, based on the command that is passed to the construtor of the class, the corresposnding function of the class is called and executed.

No comments: