The Wayback Machine - https://web.archive.org/web/20240926114043/https://www.geeksforgeeks.org/singleton-method-python-design-patterns/
Open In App

Singleton Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Singleton Design pattern | Introduction

What is Singleton Method in Python

Singleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class to create methods and specify the objects. 
Singleton Design Pattern can be understood by a very simple example of Database connectivity. When each object creates a unique Database Connection to the Database, it will highly affect the cost and expenses of the project. So, it is always better to make a single connection rather than making extra irrelevant connections which can be easily done by Singleton Design Pattern.

single-pattern-in-python

singleton-pattern

Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Now let’s have a look at the different implementations of the Singleton Design pattern. 

Method 1: Monostate/Borg Singleton Design pattern

Singleton behavior can be implemented by Borg’s pattern but instead of having only one instance of the class, there are multiple instances that share the same state. Here we don’t focus on the sharing of the instance identity instead we focus on the sharing state. 

Python
# Singleton Borg pattern
class Borg:

    # state shared by each instance
    __shared_state = dict()

    # constructor method
    def __init__(self):

        self.__dict__ = self.__shared_state
        self.state = 'GeeksforGeeks'

    def __str__(self):

        return self.state


# main method
if __name__ == "__main__":

    person1 = Borg()    # object of class Borg
    person2 = Borg()    # object of class Borg
    person3 = Borg()    # object of class Borg

    person1.state = 'DataStructures'  # person1 changed the state
    person2.state = 'Algorithms'     # person2 changed the state

    print(person1)    # output --> Algorithms
    print(person2)    # output --> Algorithms

    person3.state = 'Geeks'  # person3 changed the
    # the shared state

    print(person1)    # output --> Geeks
    print(person2)    # output --> Geeks
    print(person3)    # output --> Geeks

Output: 

Algorithms
Algorithms
Geeks
Geeks
Geeks
singleton-Design-pattern-python

Singleton-Design-pattern

Double Checked Locking Singleton Design pattern

It is easy to notice that once an object is created, the synchronization of the threading is no longer useful because now the object will never be equal to None and any sequence of operations will lead to consistent results. 
So, when the object will be equal to None, then only we will acquire the Lock on the getInstance method.

Python
# Double Checked Locking singleton pattern
import threading


class SingletonDoubleChecked(object):

    # resources shared by each and every
    # instance

    __singleton_lock = threading.Lock()
    __singleton_instance = None

    # define the classmethod
    @classmethod
    def instance(cls):

        # check for the singleton instance
        if not cls.__singleton_instance:
            with cls.__singleton_lock:
                if not cls.__singleton_instance:
                    cls.__singleton_instance = cls()

        # return the singleton instance
        return cls.__singleton_instance


# main method
if __name__ == '__main__':

    # create class X
    class X(SingletonDoubleChecked):
        pass

    # create class Y
    class Y(SingletonDoubleChecked):
        pass

    A1, A2 = X.instance(), X.instance()
    B1, B2 = Y.instance(), Y.instance()

    assert A1 is not B1
    assert A1 is A2
    assert B1 is B2

    print('A1 : ', A1)
    print('A2 : ', A2)
    print('B1 : ', B1)
    print('B2 : ', B2)

Output:  

A1 :  __main__.X object at 0x02EA2590
A2 : __main__.X object at 0x02EA2590
B1 : __main__.Y object at 0x02EA25B0
B2 : __main__.Y object at 0x02EA25B0

Creating a singleton in Python

In the classic implementation of the Singleton Design pattern, we simply use the static method for creating the getInstance method which has the ability to return the shared resource. We also make use of the so-called Virtual private Constructor to raise the exception against it although it is not much required.

Python
# classic implementation of Singleton Design pattern
class Singleton:

    __shared_instance = 'GeeksforGeeks'

    @staticmethod
    def getInstance():
        """Static Access Method"""
        if Singleton.__shared_instance == 'GeeksforGeeks':
            Singleton()
        return Singleton.__shared_instance

    def __init__(self):
        """virtual private constructor"""
        if Singleton.__shared_instance != 'GeeksforGeeks':
            raise Exception("This class is a singleton class !")
        else:
            Singleton.__shared_instance = self


# main method
if __name__ == "__main__":

    # create object of Singleton Class
    obj = Singleton()
    print(obj)

    # pick the instance of the class
    obj = Singleton.getInstance()
    print(obj)

Output:  

 __main__.Singleton object at 0x014FFE90
__main__.Singleton object at 0x014FFE90

Class diagram

Class Diagram of Singleton Design Pattern 

singleton-method-class-diagram

singleton-class-diagram

Advantages of using the Singleton Method: 

  1. Initializations: An object created by the Singleton method is initialized only when it is requested for the first time.
  2. Access to the object: We got global access to the instance of the object.
  3. Count of instances: In singleton, method classes can’t have more than one instance

Disadvantages of using the Singleton Method: 

  1. Multithread Environment: It’s not easy to use the singleton method in a multithread environment, because we have to take care that the multithread wouldn’t create a singleton object several times.
  2. Single responsibility principle: As the Singleton method is solving two problems at a single time, it doesn’t follow the single responsibility principle.
  3. Unit testing process: As they introduce the global state to the application, it makes the unit testing very hard.

Applicability

  1. Controlling over global variables: In the projects where we specifically need strong control over the global variables, it is highly recommended to use Singleton Method
  2. Daily Developers use: Singleton patterns are generally used in providing the logging, caching, thread pools, and configuration settings and are often used in conjunction with Factory design patterns.

Further read: Singleton method in Java, Singleton Design Pattern Practices with Examples



Previous Article
Next Article

Similar Reads

Singleton Pattern | C++ Design Patterns
A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have only one instance of a class, for example, a singl
11 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Singleton Method Design Pattern
Singleton Pattern is probably the most widely used design pattern. It is a simple pattern, easy to understand and to use. Sometimes it is used in excess and in scenarios where it is not required. In such cases, the disadvantages of using it outweigh the advantages it brings. For this reason, the singleton pattern is sometimes considered an antipatt
12 min read
Singleton Method Design Pattern in JavaScript
Singleton Method or Singleton Design Pattern is a part of the Gang of Four design pattern and it is categorized under creational design patterns. It is one of the most simple design patterns in terms of modeling but on the other hand, this is one of the most controversial patterns in terms of complexity of usage. Important Topics for the Singleton
10 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Singleton Design Pattern in Java
Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system. Important Topics for Singleton Method in Java Problem Statement for Singleton Method:Use Case o
5 min read
Most asked Singleton Design Pattern Interview Questions
This article comprises some of the most asked Singleton design pattern interview questions, which will help you tackle any Singleton design pattern question properly. 1. Give an example use case for the singleton design pattern.This design pattern can be useful in various scenarios, such as when you need to control access to a shared resource, mana
11 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
What is the Correlation Between System Design and Design Patterns?
System design and design patterns are closely related concepts in software engineering, with design patterns serving as reusable solutions to common design problems encountered during system design. System design and design patterns are interrelated concepts that work together to create robust and well-structured software systems. Important Topics
11 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
Data Pipeline Design Patterns - System Design
In system design, data pipeline design patterns play a crucial role in efficiently processing and transporting data across various stages of a system. These patterns help ensure scalability, reliability, and performance when managing data workflows. A well-designed data pipeline can handle large volumes of data, transform it as needed, and move it
8 min read
Singleton Pattern in Python - A Complete Guide
A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are: To limit concurrent access to a shared resource.To create a global point of access for a resource.To create just one instance of a class, thro
9 min read
Iterator Method - Python Design Patterns
Iterator method is a Behavioral Design Pattern that allows us to traverse the elements of the collections without taking the exposure of in-depth details of the elements. It provides a way to access the elements of complex data structure sequentially without repeating them.According to GangOfFour, Iterator Pattern is used " to access the elements o
4 min read
Template Method - Python Design Patterns
The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral desig
4 min read
Factory Method - Python Design Patterns
Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the client, and for creating the new type of object, the
5 min read
Abstract Factory Method - Python Design Patterns
Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try t
4 min read
Builder Method - Python Design Patterns
Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code, we can produce different types and representatio
5 min read
Adapter Method - Python Design Patterns
Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces.
4 min read
Bridge Method - Python Design Patterns
The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to organize the class hierarchy. Elements of Bridge Des
5 min read
Composite Method - Python Design Patterns
Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method
5 min read
Decorator Method - Python Design Patterns
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the
3 min read
Flyweight Method - Python Design Patterns
Flyweight method is a Structural Design Pattern that focus on minimizing the number of objects that are required by the program at the run-time. Basically, it creates a Flyweight object which is shared by multiple contexts. It is created in such a fashion that you can not distinguish between an object and a Flyweight Object. One important feature o
5 min read
Proxy Method - Python Design Patterns
The Proxy method is Structural design pattern that allows you to provide the replacement for an another object. Here, we use different classes to represent the functionalities of another class. The most important part is that here we create an object having original object functionality to provide to the outer world. The meaning of word Proxy is "i
4 min read
Command Method - Python Design Patterns
Command Method is Behavioral Design Pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests and the queuing or logging of requests. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on s
3 min read