Strategy Design Pattern

bruno at modulix onurb at xiludom.gro
Fri Apr 21 05:30:26 EDT 2006


Daniel Santa Cruz wrote:
> Hello all,
> 
> I've been trying to go over my OO Patterns book, and I decided to try
> to implement them in Python this time around.  I figured this would
> help me learn the language better.
> 
> Well, I've gotten stuck with my first go at OO patterns with Python.  I
> guess it goes without say that some of the stuff that are taken for
> granted in most of the books (ie. Interfaces, Abstract classes) don't
> really apply to Python per say, but the idea behind the patterns can be
> extracted out still. 

A good part of the GoF patterns are meant to add flexibility to static
languages - translating them directly in a dynamic language may not be
such a good idea. Regarding abstract base classes (Java's interfaces
being a special case of abc), they are mostly used in static languages
to provide support for polymorphic dispatch. This is not needed in
Python, where polymorphic dispatch is not tied to inheritance.

FWIW, it's still possible to have abc in Python:

class Abc(object):
  def abstractMethod(self, args):
    raise NotImplementedError("Abc is an abstract class")

> 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...

The first part (abstract an algorithm out of the class) is ok. The real
goal is to allow to dynamically select the algorithm to use based on
runtime conditions (ie: user prefs, platform-specific stuff, size of a
file, phase of the moon, whatnot...).

> I'm at a loss at how I can do this with Python, any pointers would be
> more than welcomed!

Hint 1: Python's functions are objects
Hint 2: Dynamically attaching a method to an object (ie : not to the
whole class) is easy as pie (search this group...).
Hint 3: Any object having a __call__() method is callable.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list