[Tutor] flyweight pattern using Mixin vs. Inheritance
Alan Gauld
alan.gauld at btinternet.com
Fri Aug 28 19:29:15 CEST 2009
"Serdar Tumgoren" <zstumgoren at gmail.com> wrote
> Given those requirements, is the Mixin approach the way to go? Either
> way, have I implemented these correctly?
I haven't looked at your code but you could use a mixin here
however I find using mixins for insantiation can bend your brain.
I tend to use them for instance behavioural type things
.
Instead I would actually use a dictionary class attribute (see the thread
on class attributes/methods)
The way I'd do it would be to store a dictionary of object instances
(using some kind of unique name/id as key). In the constructor of
each class (ie __new__() not __init__() check to see if the ID exists
in the dictionary and return the object if it does. Otherwise
continue as usual.
Something like this(untested pseudo code):
class A
instances = {}
def __new__(self, ID, *args, **kwargs):
if ID in instances:
return ID
def __init__(self, *args, **kwargs):
if ID in self.instances:
return
else:
# init as usual.
def __del__(self):
del( self.instances[self.ID] )
The __del__ can probably be implemented in the top level class
and inherited.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list