views:

48

answers:

2

Program design:

  • Class A, which implements lower level data handling
    • Classes B-E, which provide a higher level interface to A to perform various functions
      • Class F, which is a UI object that interacts with B-E according to user input

There can only be one instantiation of A at any given time, to avoid race conditions, data corruption, etc.

What is the best way to provide a copy of A to B-E? Currently F instantiates A and holds onto it for the life of the program, passing it to B-E when creating them. Alternately I could create a globally available module with a shared copy of A that everything uses. Another alternative is to make B-E subclasses of A, but that violates the constraint of only one A (since each subclass would be their own data handler, so to speak).

Language is Python 3, FWIW.

+4  A: 

Use a Borg instead of a Singleton.

>>> class Borg( object ):
...     __ss = {}
...     def __init__( self ):
...             self.__dict__ = self.__ss
...
>>> foo = Borg()
>>> foo.x = 1
>>> bar = Borg()
>>> bar.x
1
katrielalex
You learn something new every day...
Chinmay Kanchi
Interesting. So I would assume that I would make A a subclass of Borg, then B-E subclasses of A? Nice.
bk0
@bk0: well, Borg isn't a specific class so much as a design pattern; you would make `A` (whatever class it is) "Borglike" by making each instance's `__dict__` be a class variable (and therefore shared between instances). Don't subclass `A` for this; just make a new instance whenever you want one and it will magically share state with all the other instances.
katrielalex
A: 

How about using the module technique, this is much simpler.

in module "A.py"

class A(object):
   def __init__(self, ..)
       ...
a = A()

in module "B.py"

from A import a

class B(object):
   def __init__(self)
       global a
       self.a = a

The both have single instance a.

The same could be done for other classes C, D, F etc

pyfunc
Using 'global' turns my stomach. I've effectively done something similar though using 'shared.py' where F assigns an instantiation of A which gets picked up by B-E.
bk0