Design Pattern Python: Creational (Singelton) Pattern

Design Pattern Python: Creational (Singelton) Pattern


2 min read

Table of contents

No heading

No headings in the article.

What is Creational Design Pattern?

It is a unique way of object creation, making it easier for developers to create objects in a flexible and maintainable way, without tightly coupling their code to the object creation logic.

Singelton Design Pattern

Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance. This pattern is used to provide a single point of control or to ensure that a class only has one instance throughout the lifetime of a program.

A singleton class has the following properties:

  • It has a private constructor, which prevents other classes from creating instances of the singleton class.

  • It has a private static instance variable, which stores the single instance of the class.

  • It has a public static method (often called "getInstance()") that returns the single instance of the class, creating it if necessary.


            class Singleton:
                __instance = None

                def getInstance():
                    if Singleton.__instance is None:
                    return Singleton.__instance

                def __init__(self):
                    if Singleton.__instance is not None:
                        raise Exception("You cannot create multiple instances of a singleton class.")
                        Singleton.__instance = self

To use the singleton class, clients simply call the getInstance() method, which returns the single instance of the class. The first time the method is called, the instance of the class is created. Subsequent calls to the method return the same instance. This ensures that there is only one instance of the singleton class throughout the lifetime of the program.