Reading Time: 1 minutes
Strategy Design Pattern in Python
Write a Python program to implement Strategy Design Pattern.
import sys import types # if construct to select the right amount of arguments to method MethodType # MethodType binds a function to an instance of a class, or to all instances of the class. # The function being bound either gets added in the class definition, or replaces the contents of a method defined in the class. # The MethodType takes two arguments in Python 3, first, the method to be bound, second, the instance to which the method is to be bound. # In Python 2, there is third positional argument, which seeks the class to which the instance passed as second argument, belongs. if sys.version_info[0] > 2: # Python 3 createBoundMethod = types.MethodType else: def createBoundMethod(func, obj): # Python 2 return types.MethodType(func, obj, obj.__class__) class Strategy: '''Strategy Class: houses default strategy; provides mechanism to replace the execute() method with a supplied method''' def __init__(self, strategyName = 'Default Strategy', replacementFunction=None): '''If strategyName is provided, sets strategy name to string provided; If a reference to new strategy function is provided, replace the execute() method with the supplied function.''' self.name = strategyName if replacementFunction: self.execute = createBoundMethod(replacementFunction, self) def execute(self): '''Contains default strategy behavior. If a reference to a new strategy function is provided, then the body of this function gets replaced by body of supplied method''' print("Executing {}...".format(self.name)) # Behavior of Strategy One def strategyOne(self): '''Contains behavior of Strategy One.''' print("Executing {}...".format(self.name)) # Behavior of Strategy Two def strategyTwo(self): '''Contains behavior of Strategy Two.''' print("Executing {}...".format(self.name)) ## USING THE ABOVE SETUP ## # Instantiating Default Strategy defaultStrategy = Strategy() # Instantiating Strategy One strategyONE = Strategy('Strategy One', strategyOne) # Instantiating Strategy Two strategyTWO = Strategy('Strategy Two', strategyTwo) # Executing different strategies defaultStrategy.execute() strategyONE.execute() strategyTWO.execute() ### OUTPUT ### Executing Default Strategy... Executing Strategy One... Executing Strategy Two...