2 Aralık 2008 Salı

Template Design Pattern


The next step in DP land is Template Design Pattern, well what is it ? As far as i understood there is nothing special and new under the hood. You have an abstract class with methods to be overriden by its sunclasses. The main difefrence is you have a one or more template methods which draw the flow of the things. A simple example maybe :


class MainClass(object):

def operation1(self):
#do stuff

def operation2(self):
#do stuff

def __template_method(self):
self.operation1()
self.operation2()



What we did here is to supply an API for users to override the operation1 and operation2 but we want to control the overflow by template_method, if you want more extendible structure you may also make it public. Well i know that pattern i have used it in lots of places but didnt know its name :) The new thing i learned from Head First is the hook methods , you make them optional for the client code. For example:

class MainClass(object):

def operation1(self):
#do stuff

def operation2(self):
#do stuff

def hook(self):
pass

def do_you_want_hook(self):
return True

def __template_method(self):
self.operation1()
self.operation2()
if self.do_you_want_hook():
hook()


Ok the difference is if user wants something extra to be executed he/she can override hook and do the extra stuf that is needed there,otherwise that method will not be invoked (well it will be but nothing will happen).
That is all for the template pattern, we know you,you are not new here :)

Hiç yorum yok: