A factory in object-oriented programming is a design pattern that creates instances of classes. There are variations on this pattern but for my purposes, I simply refer to it as an instance factory because that is essentially what it is used for. The factory takes the responsibility of directly instantiating a class from the context that uses the factory. That context may be some function or, more often, some method of another class. The factory itself is generally a class with several static or class methods. It is these methods that construct and return instances.
So if the developer can take the responsibility of directly instantiating some class away from the method they are currently working on, what do they gain? In this case, it isn't what they gain but what they lose. They lose the direct coupling to the class in question. In most cases, a given class is going to need to create more than one type of instance throughout its' lifetime. This means that there is a dependency between the class in question, serving as the context, and the other classes that it depends on. If the class in question requires only a factory, the class then becomes loosely-coupled. This is an important design factor.
The instance factory is essentially a proxy for the act of creation. It isn't a proxy for data but for behavior. This is the sole responsibility of the factory. If a developer can see a factory invocation in code, chances are that their guess as to what it does will be correct. Since the instance factory is so specialized, it will in turn help with the distribution of responsibilities where ever it is used.
Tuesday, September 29, 2009
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment