开发者

Passing class instantiations (layering)

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 o开发者_运维技巧ne A (since each subclass would be their own data handler, so to speak).

Language is Python 3, FWIW.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜