单例模式将类的实例化限制为一个对象。 它是一种创建模式,只涉及创建方法和指定对象的一个类。
它提供了创建实例的全局访问点。
下面的程序演示了单例类的实现,并多次打印创建的实例。
class singleton:
__instance = none
@staticmethod
def getinstance():
""" static access method. """
if singleton.__instance == none:
singleton()
return singleton.__instance
def __init__(self):
""" virtually private constructor. """
if singleton.__instance != none:
raise exception("this class is a singleton!")
else:
singleton.__instance = self
s = singleton()
print s
s = singleton.getinstance()
print s
s = singleton.getinstance()
print s
执行上面的程序后,生成以下输出 -
创建的实例数量相同,并且打印的对象是同一个对象。