Credit: Concepts explained here are based on a book, “増補改訂版Java言語で学ぶデザインパターン入門”.
In this blog post, a singleton pattern is explained. This pattern is used when you want to guarantee that there are no more than one instance generated.
A singleton class creates an instance by being called get_instance method. Note that since Python does not have a built-in private methods, it is still possible to create a new instance by calling its constructor directly. If this class is written in a language that allows private methods, the constructor should be private so that the only way to create an instance is calling get_instance and no new instances are generated.
# singelton.py
class Singleton:
_singleton = None
_has_created_before = False
def __init__(self):
if not self._has_created_before:
self.create_instance()
self.update()
print("An instance is created.")
@classmethod
def update(cls):
cls._has_created_before = True
@classmethod
def create_instance(cls):
cls._singleton = cls()
@classmethod
def get_instance(cls):
return cls._singleton3
Let’s run this program. In main.py, two instances created by a class method are tested to be the same.
# main.py
from singleton import Singleton
def main():
print("Start. ")
obj1 = Singleton.get_instance()
obj2 = Singleton.get_instance()
if (obj1 == obj2):
print("obj1 and obj2 are the same instances.")
else:
print("obj1 and obj2 are the different instances.")
print("End.")
if __name__ == "__main__":
main()
Start.
obj1 and obj2 are the same instances.
End.
One benefit of Singleton pattern: it imposes a constraint that there should exit only one instance from a class. In this way, an unexpected behavior by different instances interacting with each other can be avoided such as mutual interference to a class variable.