Python Design Patterns Singleton Pattern

Python Design Patterns: Singleton Pattern

This pattern restricts the instantiation of a class to a single object. It is a creational pattern that involves only one class to create methods and specify objects.

It provides a global access point for created instances.

Python Design Patterns - Singleton

How to Implement a Singleton Class

The following program demonstrates the implementation of a singleton class, which prints the number of instances created multiple times.

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()
prints

s = Singleton.getInstance()
prints

s = Singleton.getInstance()
prints

Output

The above program produces the following output –

Python design pattern--Singleton

The number of instances created is the same, and the objects listed in the output are no different.

Leave a Reply

Your email address will not be published. Required fields are marked *