相关疑难解决方法(0)

Monostate vs. Singleton

当人们使用Monostate模式而不是singleton来维护全局对象时,会出现什么情况?

编辑:我知道Singleton和Monostate模式是什么.在很多场景中也实现了Singleton.只想知道需要实现MonoState模式的场景(案例).

例如.我需要在我的Windows窗体应用程序中维护每个屏幕的列列表.在这种情况下,我可以使用Singleton Dictionary.但是,我在静态全局var中存储了一个List,我想提供索引器(因为我需要动态地将新条目添加到列表中,如果key不存在),我可以将ScreenDetails.ScreenName指定为键并获取ScreenDetails .ColumnsTable.由于索引器无法在静态类上操作,因此我将模式更改为Monostate.

所以我想知道哪些其他场景可能迫使用户使用Monostate而不是Singletons.

language-agnostic singleton design-patterns

45
推荐指数
4
解决办法
2万
查看次数

Python单例/对象实例化

我正在学习Python,并且我一直在尝试将Singleton类型的类作为测试.我的代码如下:

_Singleton__instance = None

class Singleton:
    def __init__(self):
        global __instance
        if __instance == None:           
            self.name = "The one"
            __instance = self
        else:
            self = __instance
Run Code Online (Sandbox Code Playgroud)

这部分工作,但self = __instance部分似乎失败了.我已经包含了解释器的一些输出来演示(上面的代码保存在singleton.py中):

>>> import singleton
>>> x = singleton.Singleton()
>>> x.name
'The one'
>>> singleton._Singleton__instance.name
'The one'
>>> y = singleton.Singleton()
>>> y.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']
Run Code Online (Sandbox Code Playgroud)

有可能做我正在尝试的事情吗?如果不是,还有另一种方法吗?

欢迎任何建议.

干杯.

python singleton

6
推荐指数
2
解决办法
1万
查看次数