Singleton¶
- The singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance.
- This is useful when exactly one object is needed to coordinate actions across the system.
Common use cases of singleton pattern¶
- Configuration Settings
- Logging
- Caching and thread pool
- Database connections
Example implementation of singleton pattern¶
- Let's implement the database connection with singleton pattern
class DB:
__connection = None
@classmethod
def connect(cls):
if not cls.__connection:
print('Establishing connection...')
cls.__connection = ...
return cls.__connection
if __name__ == '__main__':
connection1 = DB.connect()
connection2 = DB.connect()
In the above code, we have called DB.connect()
twice. but, it will be create only one database connection.