Singleton Pattern Python
Singleton Design Pattern Made Easy: One Object to Rule Them All
Design patterns are like battle-tested solutions to common problems in software development. One of the simplest and most widely used patterns is the Singleton Design Pattern.
Whether youβre building a logging system, database connection, global config manager, or even a WebDriver manager β Singleton has your back.
π What is the Singleton Pattern?
The Singleton pattern ensures that a class has only one instance throughout the application and provides a global point of access to it.
π§ Simple Analogy:
Imagine your home has one Wi-Fi router. Everyone in the house uses the same router instead of buying a new one for each device. Thatβs Singleton in action!
π¦ Real-World Examples
- Remote Control β One remote, one TV.
- Election Commission β One authoritative body across a country.
- Printer Spooler β One system-wide controller for print jobs.
β When to Use Singleton?
- You need to restrict object creation to just one instance.
- You want global access to the same resource.
- Youβre working with shared resources (e.g., file systems, databases, configuration).
π‘ Benefits
- π Saves memory by reusing the same object
- π Provides consistent access across the system
- π οΈ Easy to maintain and debug
- π Useful in multi-threaded apps (with thread-safe variations)
β οΈ Be Careful
- Too many singletons = global state mess
- In multithreaded apps, make sure your Singleton is thread-safe
π§ͺ Python Code Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
print("Creating new instance...")
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
# Usage
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # Output: True
β
obj1 and obj2 refer to the same object. Only the first call creates the instance; the rest reuse it.
π‘ Pro Tip for Automation Engineers
WebDriver instance in Selenium frameworks is often implemented as a Singleton to avoid launching multiple browser sessions unnecessarily.
π Conclusion
The Singleton Pattern is simple but powerful. It promotes controlled object creation and helps in maintaining a consistent system state β especially when dealing with shared resources.
So next time you need a single point of access, give Singleton a shot!
π Letβs Connect
If you enjoyed this article or found it helpful, follow me for more insights on design patterns and automation best practices.
π LinkedIn: linkedin.com/in/hossain-mdsaddam
π» GitHub Blog: shossain786.github.io
Thanks for reading!