[Tutor] The Template Pattern

Karim karim.liateni at free.fr
Tue Dec 14 00:19:31 CET 2010


On 12/13/2010 11:47 PM, Steven D'Aprano wrote:
> 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.
>

Steven, thank you for answering ;o)

I don't want to use this pattern absolutely. But I discussed this topic 
with a C++ programmer.
He wanted to translate part of C++ code in python that implements this 
pattern in C++.
I already have implemented a Strategy pattern in python to read 
different file format into
my database and generate different output format file like the code below:

class Input(object):
     """The basic Input class, leaving out the details of the algorithm."""
     def __init__( self, strategy ):
         self.strategy = strategy
         self.lastRead = None

     def read(self, filePath):
     """Load into database memory an input file.
     @arg: filePath - string - The input file path.
     @return: The created database object.
     """
     self.lastRead = self.strategy.read()
     return self.lastRead


class InputStrategy( object ):
     """This InputStrategy class is an abstract interface to various
     read strategy objects.
     """
     def read(self, filePath):
         """Abstract method to load into database memory an input file.
         @arg: filePath - string - The input file path.
         @return: The created database object.
         """
         raise NotImplementedError

By the way, I use NotImplementedError in my abstract method of the 
abstract class. You are using TypeError exception.
Is there a general rule for that? NotImplementedError is ok?

I knew from Java experience that template method pattern is only a kind 
of particular case of Stategy where you delegate
parts of algorithm by abstract methods overriding. Indeed the base class 
implements some common features and let
derived classes implement particular parts by polymorphism.
Now with your example, I don't understand why he had problems to 
implement from C++ ?
Or perhaps is he mixing it with C++ feature template <class T> ?!

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


One more Thanks for you example Steven!
Regards
Karim


More information about the Tutor mailing list