4 Aralık 2008 Perşembe

Command pattern in Python


I continue with "x pattern in Python" series, the articles i posted here are not tutorials or some professional learning resource. I poste them here only for myself to rememer the things when i need them :) What is the command pattern and why wee need it ? Well imagine you have a class that controls some operations on files, writing , reading , closing , and maybe many more. In first sight i would complete that like this :


class FileOperator:

def operation1(self):
pass

def operation2(self):
pass

#snip snip snip ....

Well that implementation seems enough for now, but what if we want to supply a simple api to users like that


f = FileOperator()
f.process_command()


Well, with current implementation that doesnt seem to be possible, the current implementation is kind fo static and user has to know the internals of the FileOperator class. If the users want some extra functionality like undo or logging, it will not be very easy to be implemented. And every change that has to be done will effect the current client code which is not cool. Also user may want when call the process_command to execute multiple commands like write_to_file and read_contents and etc. What we will do is again the basic OOP remove the parts that can change in the future. We will remove the executer parts and wiill assing them when we need them. Ok when reading it doesnt seem so easy but the code is easier:

Here is my implementation of the Command Pattern : LINK

After that implementation you will able to do things like that :

def test_me_yo():
"""
Lets see that one
"""
tmp_file = open("some.txt","w")
tmp_file.write("hehehe\n")
tmp_file.close()

#end of initial data
#first lets read the contents of the stuff
fe = FileEditor()
fileman = FileMan("some.txt")
fread = FileReadCommand(fileman)
fwrite=FileWriteCommand(fileman)
fe.set_command(fread)
fe.process_command()

#append some info to the end of it
fe.set_command(fwrite)
fe.process_command("add some text here")
fe.set_command(fread)
fe.process_command()

#lets now go and create an command manager
cm = CommanManager()
cm.add_commanders(fwrite,fread)
fe.set_command(cm)

fe.process_command("\n Add another sting here ")
print "First undo :"
fe.undo_process()
print "Second undo :"
fe.undo_process()
print "Thirrd undo :"
fe.undo_process()

Well it is pretty pluggable design you can combine the commands you like do "undo" all the magic you need. What i learned from Design Patterns is they are based on the same principle "remove the parts that will change in the future" ,separating the concerns is very important ...

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 :)

1 Aralık 2008 Pazartesi

Factory Pattern in Python


Our next step in DP is object factories. Creating objects with if else clauses sometimes may not be very flexible for our programs. Some of the objects may neeed more complex and long initializations other maybe simple etc. Because of that it is cooler to have some methods or some classes that give you the instance you need. For exmple think about a client program which needs a slash directory or file manager. If you're trying to have your program platform independent you should have different versions for Windows and Linux based machines. Therefore when you client is initializing the File manager it should everytime do

if linux:
do sth
else:
do another


But for a framework that is not very flexible and when some code of FileManager changes (some code of initialization) you should change your client code which is not cool. It would be better if you have some class that gives you the instance you need, in our example FilemanagerFactory.get_instance() so client code will not care about the platform and other annoying stuf it will just get the instance it needs. Yep that is factory pattern ...
To demonstrate the factory thing i wrote a simple example that is responsible for creating Validators, if you have a string you get a string validator if you have an integer you have integer valiator and etc . Here is the link: LINK

To test the code you need sth like that :

from pyalgorithm.dp.factory import *

def test_facto():
my_value = "Some_strrrrrrrrr"
factory = ValidatorFactory()
validator = factory.create(my_value)
print validator.validate()

my_value = 11
validator = factory.create(my_value)
print validator.validate()

my_value = 11.12
validator = factory.create(my_value)
if not validator:
print "No object created ..."

Well that is all, factory pattern may not be very important for little projects but if you have to initialize lots of classes it maybe wisw to have some class to do that for you.