Strategy Design Pattern

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Apr 21 05:02:36 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.  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...
>
> I'm at a loss at how I can do this with Python, any pointers would be
> more than welcomed!


This is my understanding of the Strategy Pattern:

(Perhaps I have a SudokuSolver class that will solve *any* Sudoku
puzzle, but it's very slow for simple puzzles because of some
unavoidable overhead related only to the more difficult puzzles - so I
want to try a simpler but faster method first, if it doesn't succeed
then use the more complex method.)

class SudokuGrid(object):
    def __init__(self, solver=None):
        self.grid = [[-1]*9]*9
        if solver is not None:
            self.solver = solver
        else:
            self.solver = SimpleSudokuSolver()

    def solve(self):
        self.solver.sudoku = self
        self.solver.solve()

class SimpleSudokuSolver(object):
    sudoku = None
    def solve(self):
        print 'solving %s ...simple algorithm...' % repr(self.sudoku)

class DifficultSudokuSolver(object):
    sudoku = None
    def solve(self):
        print 'solving %s ...difficult algorithm...' %
repr(self.sudoku)

s = SudokuGrid()

s.solve()

s.solver = DifficultSudokuSolver()

s.solve()

solving <__main__.SudokuGrid object at 0x0117D390> ...simple
algorithm...
solving <__main__.SudokuGrid object at 0x0117D390> ...difficult
algorithm...

HTH

Gerard




More information about the Python-list mailing list