Factory pattern implementation in Python

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Dec 4 18:30:24 EST 2006


<bearophileHUGS at lycos.com> wrote in message 
news:1165263327.407166.276160 at l12g2000cwl.googlegroups.com...
> Dennis Lee Bieber:
>> Presuming the <event x> is a type code I'd just set up a list of 
>> functions:
>> Then create a dictionary of them, keyed by the <event x> code
>> processors = { "1" : process_1,
>>         "2" : process_2,
>> ....
>> "x" : process_x }
>
> Just a dict of functions was my solution too, I think avoiding more
> complex solutions is positive.
>
> Bye,
> bearophile
>
I think I'd go one step up the OO ladder and match each event code to a 
class.  Have every class implement a staticmethod something like 
"load(stream)" (using pickle terminology), and then use a dict to dispatch.

eventTypes = { "1" : BlahEvent, "2" : BlehEvent, "3" : BelchEvent, "4" : 
BlechEvent }

eventObj = eventTypes[ stream.read(1) ].load( stream )

Now transcending from plain-old-OO to Pythonic idiom, make this into a 
generator:

eventTypes = { "1" : BlahEvent, "2" : BlehEvent, "3" : BelchEvent, "4" : 
BlechEvent }
def eventsFromStream(stream):
    while not stream.EOF:
        evtTyp = stream.read(1)
        yield eventTypes[evtTyp].load(stream)

and then get them all in a list using

list( eventsFromStream( stream ) )

-- Paul





More information about the Python-list mailing list