0% found this document useful (0 votes)
8 views

3-DesignPatterns Part 2

The document discusses the command design pattern in Python. It provides an introduction to the pattern, explaining the client, invoker, and receiver components. It then gives a sample Python implementation of a light switch using the command pattern, with classes for the switch, light, and on/off commands.

Uploaded by

ali sağoan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

3-DesignPatterns Part 2

The document discusses the command design pattern in Python. It provides an introduction to the pattern, explaining the client, invoker, and receiver components. It then gives a sample Python implementation of a light switch using the command pattern, with classes for the switch, light, and on/off commands.

Uploaded by

ali sağoan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Design Patterns in Python

DP# 2
Command Pattern

Introduction

As per Wikipedia:

“In object-oriented programming, the command


pattern is a design pattern in which an object is used
to represent and encapsulate all the information
needed to call a method at a later time. This
information includes the method name, the object that
owns the method and values for the method
parameters.

Command pattern is one of the design patterns that are categorized under
‗Observer‘ design pattern. In command pattern the object is encapsulated in the
form of a command, i.e., the object contains all the information that is useful to
invoke a method anytime user needs. To give an example, let say we have a user
interface where in the background of the interface would turn into RED if the button
on the user interface named ‗RED‖ is clicked. Now the user is unaware what classes
or methods the interface would call to make the background turn RED, but the
command user sends (by clicking on ‗RED‘ button) would ensure the background is
turned RED. Thus command pattern gives the client (or the user) to use the
interface without the information of the actual actions being performed, without
affecting the client program.

The key to implementing this pattern is that the Invoker object should be kept
away from specifics of what exactly happens when its methods are executed. This
way, the same Invoker object can be used to send commands to objects with
similar interfaces.

15 www.testingperspective.com
Design Patterns in Python

Command Pattern is associated with three components, the client, the invoker, and
the receiver. Let‘s take a look at all the three components.

 Client: the Client represents the one that instantiates the encapsulated object.
 Invoker: the invoker is responsible for deciding when the method is to be
invoked or called.
 Receiver: the receiver is that part of the code that contains the instructions to
execute when a corresponding command is given.

A Sample Python Implementation

For demonstrating this pattern, we are going to do a python implementation of an


example present on Wikipedia in C++/Java/C#.

Example description

 It's the implementation of a switch


 It could be used to switch on/off
 It should't be hard-coded to switch on/off a particular thing (a lamp or an
engine)

Python Code
class Switch:
""" The INVOKER class"""

def __init__(self, flipUpCmd, flipDownCmd):


self.__flipUpCommand = flipUpCmd
16 www.testingperspective.com
Design Patterns in Python

self.__flipDownCommand = flipDownCmd

def flipUp(self):
self.__flipUpCommand.execute()

def flipDown(self):
self.__flipDownCommand.execute()

class Light:
"""The RECEIVER Class"""
def turnOn(self):
print "The light is on"

def turnOff(self):
print "The light is off"

class Command:
"""The Command Abstract class"""
def __init__(self):
pass
#Make changes

def execute(self):
#OVERRIDE
pass

class FlipUpCommand(Command):
"""The Command class for turning on the light"""

def __init__(self,light):
self.__light = light

def execute(self):
self.__light.turnOn()

class FlipDownCommand(Command):
"""The Command class for turning off the light"""

def __init__(self,light):
Command.__init__(self)
self.__light = light

def execute(self):
self.__light.turnOff()

class LightSwitch:
""" The Client Class"""

17 www.testingperspective.com
Design Patterns in Python

def __init__(self):
self.__lamp = Light()
self.__switchUp = FlipUpCommand(self.__lamp)
self.__switchDown = FlipDownCommand(self.__lamp)
self.__switch = Switch(self.__switchUp,self.__switchDown)

def switch(self,cmd):
cmd = cmd.strip().upper()
try:
if cmd == "ON":
self.__switch.flipUp()
elif cmd == "OFF":
self.__switch.flipDown()
else:
print "Argument \"ON\" or \"OFF\" is required."
except Exception, msg:
print "Exception occured: %s" % msg

# Execute if this file is run as a script and not imported as a module


if __name__ == "__main__":

lightSwitch = LightSwitch()

print "Switch ON test."


lightSwitch.switch("ON")

print "Switch OFF test"


lightSwitch.switch("OFF")

print "Invalid Command test"


lightSwitch.switch("****")

18 www.testingperspective.com

You might also like