单例模式

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

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

如何实现一个单例类?

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

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

执行上面的程序后,生成以下输出 -

创建的实例数量相同,并且打印的对象是同一个对象。


上一篇:模型视图控制器(MVC)模式

下一篇:工厂模式

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程