Python设计模式 单例


此模式将类的实例化限制为一个对象。它是一种创建模式,只涉及一个类来创建方法和指定对象。

它提供了对创建的实例的全局访问点。

Singleton Pattern

如何实现单例类?


下面的程序演示了单例类的实现,它打印了多次创建的实例。

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

上述程序产生如下输出:

Implementation of Singleton

创建的实例数量相同,输出中列出的对象没有差异。