What is a singleton?
Singleton pattern is a software design pattern, singleton object class in this mode can only be one instance. When some parts of the project does not affect the execution of the code, such as logging, a singleton design pattern is preferably a method. In addition there can be obtained using the singleton global state of cache, load balancing, route map.
Singleton Pattern Classification
1. lazy singleton
need to call the relevant methods to create a single example, high resource utilization, increase the cost of multi-threaded access.
singleton_lazy.py
class Singleton_Lazy():
__instance = None
def __init__(self):
pass
@staticmethod
def create_instance():
if not Singleton_Lazy.__instance:
Singleton_Lazy.__instance = Singleton_Lazy()
return Singleton_Lazy.__instance
test_lazy.py
from danli.singleton_lazy import Singleton_Lazy
dan1 = Singleton_Lazy().create_instance()
dan2 = Singleton_Lazy().create_instance()
print(dan1)
print(dan2)
dan3 =Singleton_Lazy()
dan4 =Singleton_Lazy()
print(dan3)
print(dan4)
2. hungry Singleton
when initialized automatically create a singleton class, to ensure thread safety, save operating time, reduce resource utilization.
singleton_hunger.py
class Singleton_Hunger():
instance = None
class __Singleton():
pass
def __new__(cls, *args, **kwargs):
if not Singleton_Hunger.instance:
cls.instance = Singleton_Hunger.__Singleton()
return cls.instance
test_hunger.py
from singleton_hunger import Singleton_Hunger
dan1 = Singleton_Hunger()
dan2 = Singleton_Hunger()
print(dan1)
print(dan2)
Singleton advantages
1. The presence of only a single singleton object
2. The reduced memory consumption, increased resource utilization
Singleton disadvantages
Example 1. Since the single globally shared mode, the state maintenance singleton object requires special care.
2. Usually singleton object heavy duties, contrary to the "principle of the single function" to some extent.
Global state is a place where we need to be vigilant in programming, some code in the project may affect the global state, resulting in unnecessary trouble. In the actual development, we need to avoid abuse Singleton pattern.
Application singleton pattern design logger -> Click here