diff --git a/factory.py b/factory.py index 3dbd617..717497e 100644 --- a/factory.py +++ b/factory.py @@ -29,5 +29,5 @@ def create_pizza(pizza_type): if __name__ == '__main__': for pizza_type in ('HamMushroom', 'Deluxe', 'Hawaiian'): - print('Price of {0} is {1}'.format(pizza_type, PizzaFactory.create_pizza(pizza_type).get_price()) + print('Price of {0} is {1}'.format(pizza_type, PizzaFactory.create_pizza(pizza_type).get_price())) diff --git a/strategy.py b/strategy.py index 053e0c8..85a968a 100644 --- a/strategy.py +++ b/strategy.py @@ -5,21 +5,21 @@ def __init__(self, func=None): self.execute = func def execute(self): - print "Original execution" + print self -def executeReplacement1(self): +def execute_replacement1(): print "Strategy 1" -def executeReplacement2(self): +def execute_replacement2(): print "Strategy 2" if __name__ == "__main__": strat0 = StrategyExample() - strat1 = StrategyExample(executeReplacement1) - strat2 = StrategyExample(executeReplacement2) + strat1 = StrategyExample(execute_replacement1) + strat2 = StrategyExample(execute_replacement2) strat0.execute() strat1.execute() @@ -27,28 +27,31 @@ def executeReplacement2(self): # -------------------- With classes -------------------- +# Interface +class StrategicAlternative(object): + def the_method(self, some_arg, obj): + raise NotImplementedError("Must subclass me") -class AUsefulThing(object): - def __init__(self, aStrategicAlternative): - self.howToDoX = aStrategicAlternative - - def doX(self, someArg): - self. howToDoX.theAPImethod(someArg, self) +class Strategy(object): + def __init__(self, the_class): + self.strategy = the_class - -class StrategicAlternative(object): - pass + def do_something(self, some_arg): + self.strategy.the_method(some_arg, self) class AlternativeOne(StrategicAlternative): - def theAPIMethod(self, someArg, theUsefulThing): - pass # an implementation + def the_method(self, some_arg, obj): + print self, some_arg class AlternativeTwo(StrategicAlternative): - def theAPImethod(self, someArg, theUsefulThing): - pass # another implementation + def the_method(self, some_arg, obj): + print self, some_arg + +t = Strategy(AlternativeOne()) +t.do_something('Strategy 1') -t = AUsefulThing(AlternativeOne()) -t.doX('arg') +t = Strategy(AlternativeTwo()) +t.do_something('Strategy 2')