Factory classes (was: Re: [Tutor] Java and Python (was: Iterators))
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 4 Sep 2002 01:41:27 -0700 (PDT)
On Tue, 3 Sep 2002, Erik Price wrote:
>
> On Tuesday, September 3, 2002, at 10:35 AM, alan.gauld@bt.com wrote:
>
> > Usiakly the way to deal with class explosions is to define a
> > function (or factory class) which takes the parameters in,
> > figures out which kind of class you really need and hands
> > you a pointer to it:
>
> What is a factory class? I have seen this term before, but I'm not sure
> how it is different from any other class. Don't all class definitions
> create instances for you (handing you a reference to the instance)?
Hi Erik,
The Portland Patterns Repository collects descriptions of these nebulous
design patterns. I did a quick search and found:
http://c2.com/cgi/wiki?ClassFactory
Admittedly, it's a little dense, and doesn't have enough Python. *grin*
What may be even better for Python programmers might be Bruce Eckel's
"Thinking In Python", which is an online book on exploring design patterns
in Python:
http://www.mindview.net/Books/TIPython
In particular, Chapter 5 in Eckel's book talks about factories, and looks
really nice.
There are a few examples of factories in Python's standard library. One
notorious one includes the xml.sax.make_parser() function that
manufactures XML parser objects for us. make_parser() is a "factory
function",
http://c2.com/cgi/wiki?FactoryFunction
http://www.python.org/doc/lib/module-xml.sax.html
that will try its best to give us back a parser object. It's only purpose
in life is to pick among several potential choices and give us something
reasonable to work with.
(But by default, I think it's only choice is the 'pyexpat' parser based on
a C extension module. What makes make_parser() notorious is that, when
people install Python on their own systems, they often forget to install
expat, which means that make_parser() has no way of making an xml parser
object for us.)
The 'pyxml' project provides a few more implementations of XML parsers, as
well as the '4suite' XML modules. As far as we're concerned, though,
xml.sax.make_parser() manufactures us an xml parser object, and we usually
shouldn't care exactly where it comes from or how it got constructed.
Hope this helps!