单例模式:PYTHON

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boyun58/article/details/83268611

单例模式


单例模式只能允许类的实例化为一个对象。 它是一种创建模式,只涉及创建方法和指定对象的一个类。它提供了创建实例的全局访问点。

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("单例模式已创建,不能再次创建")
      else:
         Singleton.__instance = self
single = Singleton()
print(single)

single = Singleton.getInstance()
print(single)

single = Singleton.getInstance()
print(single)

#应用于只能存在一个对象场景

猜你喜欢

转载自blog.csdn.net/boyun58/article/details/83268611