简体   繁体   中英

Python singleton design pattern - static method vs class method appraoch

Foll. is a sample singleton design pattern implementation using static method. My question is - what difference would it have made if we use class method instead of static method?

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

In Singleton Design Pattern we create only one instance of a class that is implemented in the above implementation.

We should use the static method here because the static method will have the following benefits: A class method can access or modify class state while a static method can't access or modify it and we don't want to modify anything here we just want to return the singleton instance. In general, static methods know nothing about the class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM