[Tutor] Re: Factory classes

Erik Price erikprice@mac.com
Wed, 4 Sep 2002 08:37:01 -0400


On Wednesday, September 4, 2002, at 04:41  AM, Danny Yoo wrote:

> Admittedly, it's a little dense, and doesn't have enough Python.  
> *grin*

I agree.

> 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.

I had forgotten about this book.  I was going to read it a while ago 
but I put it off to learn the basics of Python first.  I am going to 
start reading it now.

> 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.

 From all of the input on this list (thanks everyone), I think I've put 
together what a factory class is.  It's a kind of tool which 
dynamically (at runtime) makes a decision and based on that decision 
instantiates a certain kind of class, which depends on the decision.  
But what I'm not entirely sure of is the why.

When I first grokked the concept of OO it was from a script that Kirby 
Urner posted to this list, and then Alan Gauld explained polymorphism 
to me (I read that part of his tutor).  Eventually I came to understand 
that one of the reasons that polymorphism is considered important is 
that you don't need to write code like this:

if (object is this):
   do this
else if (object is that):
   do that
else if (object is another thing):
   do the other thing
else:
   do yet some other thing

Pardon me for saying it but it sounds like a Factory Class does 
something similar to the above!  Is there something that I'm missing, 
or does the functionality of a Factory Class contradict the point of 
having similarly-named methods in different classes and subclasses so 
that we can use different kinds of objects in the same chunk of client 
code?

popcorn.eat()
apple.eat()
sushi.eat()

(Different objects altogether but all have an "eat()" method which can 
be called, ie in a loop.)




Erik




--
Erik Price

email: erikprice@mac.com
jabber: erikprice@jabber.org