In the 2009 Wikipedia entry for the Strategy Pattern, there's a example written in PHP.
Most other code samples do something like:
a = Context.new(StrategyA.new)
a.execute #=> Doing the task the normal way
b = Context.new(StrategyB.new)
b.execute #=> Doing the task alternatively
c = Context.new(StrategyC.new)
c.execute #=> Doing the task even more alternative
In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do.
Update: Can it be shorter using first-class functions in Python?
Best Solution
The example in Python is not so different of the others. To mock the PHP script:
Output:
The main differences are:
if func == None
pattern can be used for that).Note that there are 3 ways to dynamically add a method in Python:
The way I've shown you. But the method will be static, it won't get the "self" argument passed.
Using the class name:
StrategyExample.execute = func
Here, all the instance will get
func
as theexecute
method, and will getself
passed as an argument.Binding to an instance only (using the
types
module):strat0.execute = types.MethodType(executeReplacement1, strat0)
or with Python 2, the class of the instance being changed is also required:
strat0.execute = types.MethodType(executeReplacement1, strat0, StrategyExample)
This will bind the new method to
strat0
, and onlystrat0
, like with the first example. Butstart0.execute()
will getself
passed as an argument.If you need to use a reference to the current instance in the function, then you would combine the first and the last method. If you do not:
You will get:
So the proper code would be:
This will output the expected result:
Of course, in the case the functions cannot be used stand alone anymore, but can still be bound to any other instance of any object, without any interface limitation.