弗洛尔。是一个使用静态方法的单例设计模式实现示例。我的问题是-如果我们使用类方法而不是静态方法,会有什么不同?
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发布于 2019-08-06 15:04:43
在单例设计模式中,我们只创建在上述实现中实现的类的一个实例。
我们应该在这里使用静态方法,因为静态方法有以下优点:类方法可以访问或修改类状态,而静态方法不能访问或修改它,我们不想在这里修改任何东西,我们只想返回单例实例。一般来说,静态方法对类状态一无所知。它们是实用程序类型的方法,接受一些参数并对这些参数进行操作。另一方面,类方法必须将class作为参数。
https://stackoverflow.com/questions/57369310
复制相似问题