Strategy Design Pattern
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Apr 21 16:13:53 EDT 2006
In <1145597529.217734.25600 at g10g2000cwb.googlegroups.com>, Daniel Santa
Cruz wrote:
> In the specific case of the Strategy pattern, I think the goal is to
> abstract out of the class an algorithm that can then be reused by some
> of the inherited classes. This way we don't repeat ourselves. Maybe I
> got this all wrong...
IMHO yes. The goal isn't to reuse the algorithm elsewhere but to plug in
different algorithms into the "main class", which is called `context` in
the GoF book.
> Abstract Base Class: Duck
> + FlyBehavior _fly
> + swim()
> + fly() -> calls _fly.fly()
>
> Interface: FlyBehavior
> + fly()
>
> Concrete Interface FlyHigh (implements FlyBehavior): + fly()
>
> Concrete Class Duck1 (Inherits Duck): + Constructor: _fly = new
> FlyHigh()
No need to make a subclass of `Duck` and the base class should not be
abstract but take a strategy in the constructor instead.
Silly, contrived example with ducks (the `context`):
class Duck(object):
def __init__(self, fly_strategy=lambda duck: None):
self._fly = fly_strategy
self.battery = 100.0 # Percent.
def fly(self):
self._fly(self)
A dumb strategy:
def flap_as_fast_as_you_can(duck):
duck.battery -= 5
And a more sophisticated one:
def ExploitThermodynamics(object):
def __init__(self):
# Initialize data structures to keep track of wind, target etc.
def __call__(self, duck):
# Check wind, update data and change the heading of the duck
# accordingly.
duck.battery -= used_power
Now some ducks:
no_fly_duck = Duck()
fast_but_soon_tired_duck = Duck(flap_as_fast_as_you_can)
gliding_duck = Duck(ExploitThermodynamics())
If the `strategy` is a callable one can decide if a simple function is
sufficient or if the `strategy` needs some state that must be preserved
between calls to the strategy object.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list