Python单例设计模式-静态方法与类方法方法

时间:2019-08-06 05:12:40

标签: python python-3.x design-patterns singleton

伙计。是使用静态方法的示例单例设计模式实现。我的问题是-如果使用类方法而不是静态方法,会有什么不同?

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

1 个答案:

答案 0 :(得分:0)

在Singleton设计模式中,我们仅创建在上述实现中实现的类的一个实例。

我们应该在此处使用static方法,因为static方法将具有以下好处: 类方法可以访问或修改类状态,而静态方法不能访问或修改类状态,我们不想在这里修改任何东西,我们只想返回单例实例。 通常,静态方法对类状态一无所知。它们是使用一些参数并在这些参数上起作用的实用程序类型方法。另一方面,类方法必须将类作为参数。

相关问题