Design Pattern: Factory Method
2010/09/08
This pattern is used when we have a set of cases that create different classes at the same time. That is, we can abstract a base class which knows when to create, but not what to create. So, what we do is provide the base class with a method to create, and allow the subclasses to override the method.
I dislike the examples given in Wikipedia and GoF, as they do not seem to emphasize that the subclasses should all have a common aspect to their creation, and instead simply show a set of classes which fulfill a given interface differently. So take the following example with somewhat more dubiousness than naturally comes to my writing.
>>> class Base(object):
… def __init__(self, x):
… self.x=x
… def create(self):
… return self.specificCreation(self.x)
… class S1(Base):
… def specificCreation(self, x): return ‘S1′
… class S2(Base):
… def specificCreation(self, x): return ‘S2 w/ %s’%(x)
… s1=S1(4)
… s1.create()
0: ‘S1′
>>> s2=S2(4)
>>> s2.create()
1: ‘S2 w/ 4′
- This pattern is useful in framework code, where a user-defined class which implements a framework-defined interface can be inserted into the running of the framework.
- This is also useful when testing dangerous code (for instance, when reading from twitter).
- It is sometimes used without polymorphism as it gives a descriptive name to the creation and encapsulates it.