Sitemap
Vivek Pradhan

Vivek Pradhan

Expert in cutting-edge tech trends. Sharing insights on Medium to inspire the next-gen tech innovators.

Singleton pattern

1 min readJan 31, 2023

--

The Singleton pattern is a design pattern that restricts a class to having only one instance and provides a single point of access to it. This is useful when you only need one instance of a class to control the action throughout the execution of a program.

Get Vivek Pradhan’s stories in your inbox

Join Medium for free to get updates from this writer.

To implement the Singleton pattern in Python, you can follow these steps:

  1. Define a class with the __new__ method overridden to ensure that only one instance of the class can be created.
class Singleton:
_instance = None

def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance

2. Add the instance attributes and methods to the class as desired.

class Singleton:
_instance = None

def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance

def some_business_logic(self):
# implementation of business logic
pass
  1. To use the singleton class, simply create an instance of it:
s = Singleton()
s.some_business_logic()

Note: In Python, the singleton pattern can also be implemented by using metaclasses, but the above approach is the most common one.

--

--

Vivek Pradhan
Vivek Pradhan

Written by Vivek Pradhan

Expert in cutting-edge tech trends. Sharing insights on Medium to inspire the next-gen tech innovators.