[Tutor] flyweight pattern using Mixin vs. Inheritance

Serdar Tumgoren zstumgoren at gmail.com
Fri Aug 28 18:01:31 CEST 2009


Hi everyone,

Based on some earlier list advice, I went back to the drawing board
and started testing various approaches to adding the "flyweight"
pattern to my classes.

To recap, I have a bunch of campaign finance-related classes and
subclasses (Committee, HouseCommittee, PresidentialCommittee,
Candidate, CampaignReport, etc.), and I'm trying to add in the ability
for a class to check for a unique instance of itself before creating a
new instance.

So if I have a committee named "Pac1", I want to check if that
committee has previously been created. If it does exist, I want to
return the "Pac1" instance; otherwise, I want to create the "Pac1"
instance.

The closest description I could find to this pattern was the
"flyweight" (described here:
http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#behavioural-patterns),
though it appears that this pattern relates as much (or more?) to
efficient memory usage than to the notion of only creating a new
instance if an identical one does not already exist. (If there's a
name for the latter piece of this pattern, please let me know so I can
avoid typing that phrase over and over again!)

I pasted my test code for two approaches to solving this problem, one
using a Mixin class and another using Inheritance.
http://pastebin.com/m3252c407

I'm not certain I'll need this functionality on all occasions, and not
all of my classes/subclasses require this behavior.

Given those requirements, is the Mixin approach the way to go? Either
way, have I implemented these correctly?

Also,  for purposes of the test, please note that I commented out the
weakref usages (which kind of defeats the purpose of the flyweight
pattern, right?).  It was easier to wrap my brain around this when the
instance ids remained the same.  I found that when using weakref, the
ids changed (even for what should have been the same instance). Is
that due to the nature of how garbage collection works with weakref?
Or perhaps I'm not implementing this pattern correctly?

Hence my asking you all!

As always, any and all advice is appreciated.

Serdar


More information about the Tutor mailing list