## page was renamed from zhArticleTemplate ##language:zh #pragma section-numbers on -- flyaflya [<<DateTime(2005-08-04T09:09:28Z)>>] <<TableOfContents>> == 模式名称 == === 意图 === 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 === 代码 === {{{ #!python class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def spam(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) # Test it s1 = Singleton() print id(s1), s1.spam() s2 = Singleton() print id(s2), s2.spam() # Sample output, the second (inner) id is constant: # 8172684 8176268 # 8168588 8176268 }}} === 另一个实现代码 === 从[[http://members.chello.nl/f.niessink/|TaskCoach]]的代码中摘抄,因此许可证为GPL。 -- QiangningHong {{{ #!python class Singleton(type): """Singleton Metaclass""" def __init__(cls, name, bases, dic): super(Singleton, cls).__init__(name, bases, dic) cls.instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance }}} 使用方法: {{{ #!python class MyClass(object): __metaclass__ = Singleton ob1 = MyClass() ob2 = MyClass() assert ob1 is ob2 }}} === 例子 === ## 实用的代码演示 '''声明''' {{{#!python }}} '''使用情景''' {{{ #!python }}} === 特殊说明 === * 例如:MFC中的App类,一般程序中用到的全局变量。