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.

Hiç yorum yok: