OO conventions
Alex Martelli
aleaxit at yahoo.com
Sat Feb 4 10:33:14 EST 2006
Daniel Nogradi <nogradi at gmail.com> wrote:
...
> So after all, what is a 'factory' or 'factory function'?
A brief explanation in Python terms is at
http://www.aleax.it/ep03_pydp.pdf -- "pages" (slides) 37-44 (the rest of
the presentation is about an even more fundamental design pattern,
"template method"). A far more extensive essay can be found, for
example, at
http://gsraj.tripod.com/design/creational/factory/factory.html -- it
names the pattern "factory method", not "factory function" ("method" is
probably a more widespread name for it) and presents examples in Java
and Corba IDL.
Anyway, trying to summarize:
- "what": any function or method or other callable whose task it
is to build and return new objects can be called "a factory";
- sometimes a factory may get away with returning an existing
object for recycling "as if" it was a new one, saving some
resources, and this is one advantage;
- a factory may choose what exact type of object to build and return
based on arguments or other circumstances, and this is a second
advantage.
"Program to an interface, not to an implementation" -- the key
underlying principle ot the gang of 4's "Design Patterns" book.
If you build an object of a specific given type ("new Foo" in Java
or C++), you're hardwiring the choice of implementation (the
exact concrete type); delegating the building to a method or
function frees your application from such hardwiring and lets
it be concentrated (if needed at all) in one spot (the factory).
[[With the "registry" pattern you may even be able to remove
any hardwiring, but that's a pretty advanced and subtle idea]].
Alex
More information about the Python-list
mailing list