1

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
3
  • you better create single instance using __new__ method Commented Aug 6, 2019 at 5:19
  • If you use clsmethod, then you don't need to type Singleton on each line, just replace it with cls. Since classmethod accepts cls as first argument Commented Aug 6, 2019 at 5:21
  • stackoverflow.com/questions/136097/… Commented Aug 6, 2019 at 6:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Static method can access and modify the class state using the ClassName

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.