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

Hiç yorum yok: