FAQ What is a factory
From DANSE
A factory is any function (or any other callable object, such as a class object or a functor) that creates an object and returns it to the caller. There are many ways to implement factories in Python. The first way is so simple, you probably never realized you were using a factory:
1. Whenever you declare a class, the resulting object is a factory: it makes instances of the class.
class A(object): # When this line is executed, a callable object named A is made
def __init__( self):
return
The object named A is a factory for making objects; the class of the objects that that factory makes is class A.
>>> myA = A() # This calls the class object "A" to make a new A object for you.
2. A factory could be a simple function. This example assumes the previous class declaration is in a module named A.py:
def AFactory_1():
from A import A
a = A()
return a
Here's how this would get used:
>>> myA = AFactory_1() >>> print myA.__class__.__name__ A
3. A factory could also be another class in its own right, as long that class supplies a function named __call__ (any such class is called a functor). One purpose of having all these options is to allow arbitrarily complicated creation schemes. Here's a class that creates objects of class A. All of those objects are one and the same object. That is, every instance from this factory shares the same state:
class AFactory_2( object):
theInstance = None
def __call__( self):
if self.theInstance is None:
from A import A
self.theInstance = A()
a = self.theInstance
return a
Here's how that would be used:
>>> afactory = AFactory_2() >>> a1 = afactory() >>> a2 = afactory() >>> a1 is a2 True >>> a1 <__main__.A instance at 0x2a955e3368> >>> a2 <__main__.A instance at 0x2a955e3368>
Note that in this example, every time you ask the afactory for another A, you get exactly the same instance of a. Factories make it easy to use tricks like this. Whether those tricks are a good idea is another question.
