Hierarchy / Flyweight / Instancing Problem in Python

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2009-03-26T10:45:11Z Indexed on 2010/04/18 20:03 UTC
Read the original article Hit count: 330

Filed under:
|
|

Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:

1.A
1.B
1.C
2.A
3.D
4.B
5.F

(This is hard to illustrate - each number is the parent, each letter is the child).

  1. Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once.

  2. The hierarchy needs to be easy to navigate.

  3. Children in the hierarchy need to have just one parent.

  4. Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy.

  5. There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy).

  6. 'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ).

  7. It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change.

Hope this isn't too abstract to illustrate the problem.

What would be the best way of solving this? (Then I'll post my solution)

Here's an example script:

one = Number('one')
a = Letter('a')
one.addChild(a)
two = Number('two')
a = Letter('a')
two.addChild(a)

for child in one:
    child.method1()
for child in two:
    print '%s' % child.method2()

© Stack Overflow or respective owner

Related posts about python

Related posts about design