[Tutor] The Template Pattern

Steven D'Aprano steve at pearwood.info
Mon Dec 13 23:47:27 CET 2010


Karim wrote:
> 
> Hello all,
> 
> I am seeking for information about the template pattern applied to python.
> Could you explain some implementation or anything else? it would be 
> helpful.

Design patterns are means to an end, not an end in themselves. You 
shouldn't say "I want to use the template pattern", you should say "I 
want to solve this problem, what solution is appropriate?" and then only 
use the template pattern if it is appropriate.

In any case, the template design pattern is one of the simpler design 
patterns. Here's an example, adapted from Wikipedia's article on the 
Template Method Pattern:


class AbstractGame:
     """An abstract class that is common to several games in which
     players play against the others, but only one is playing at a
     given time.
     """
     def __init__(self, *args, **kwargs):
         if self.__class__ is AbstractGame:
             raise TypeError('abstract class cannot be instantiated')

     def playOneGame(self, playersCount):
         self.playersCount = playersCount
         self.initializeGame()
         j = 0
         while not self.endOfGame():
             self.makePlay(j)
             j = (j + 1) % self.playersCount
         self.printWinner()

     def initializeGame(self):
         raise TypeError('abstract method must be overridden')

     def endOfGame(self):
         raise TypeError('abstract method must be overridden')

     def makePlay(self, player_num):
         raise TypeError('abstract method must be overridden')

     def printWinner(self):
         raise TypeError('abstract method must be overridden')


Now to create concrete (non-abstract) games, you subclass AbstractGame 
and override the abstract methods.

class Chess(AbstractGame):
     def initializeGame(self):
         # Put the pieces on the board.
         ...

     def makePlay(player):
         # Process a turn for the player
         ...

etc.




-- 
Steven


More information about the Tutor mailing list