The singleton pattern Maybe the simplest design pattern , Singletons are very generic objects . Allows you to guarantee that a class has only one instance , And provide a global node to access the instance .
We can think of the captain of a ship as a real-life example of the singleton model . On board , He is in charge . He is responsible for important decisions , Because of this responsibility , He received some requests .
As mentioned earlier , One use case of the singleton pattern is to create a single object that maintains the global state of the program . Other possible use cases are as follows :
class Singleton:
"""Definition of a Singleton object."""
singleton_instance = None
def __init__( self):
"""
Override the initialization
mechanism, returning only the single instance.
"""
...
@ staticmethod
def get_singleton():
"""
Method for fetching the Singleton instance.
Is static so that it can be accessed everywhere.
"""
...
@ staticmethod
def update_singleton( val):
"""
Method for setting value of Singleton instance.
Is static so that it can be accessed everywhere.
"""
...
Stored in Singleton The data in the instance is arbitrary . It is important to , Regardless of the data , What about the caller and the range ,Singleton Object will return the same instance . This makes the unit useful in implementing things such as global settings or run configuration .
Use the following code snippet to play Active Singleton Realization . Try using data structures ( For example, a dictionary ) Replace variable Singleton_instance, And look at Getter and Setter How to change the implementation of . Try writing some shares Singleton Function of instance .
class Singleton:
"""Definition of a Singleton object."""
# Maintain state of Singleton
singleton_instance = None
def __init__( self):
"""Override the initialization mechanism."""
if Singleton. singleton_instance is None:
Singleton. singleton_instance = self
@ staticmethod
def get_singleton():
"""
Method for fetching the Singleton instance.
Is static so that it can be accessed everywhere.
"""
if Singleton. singleton_instance is None:
Singleton() # Call __init__ to initialize instance
return Singleton. singleton_instance
@ staticmethod
def update_singleton( val):
"""
Method for setting value of Singleton instance.
Is static so that it can be accessed everywhere.
"""
if Singleton. singleton_instance is None:
Singleton() # Call __init__ to initialize instance
Singleton. singleton_instance = val
Singleton. update_singleton( "Michael")
print( "Value in Singleton instance is: " + Singleton. get_singleton())
Singleton() # Try to create a new Singleton instance
print( "Value in Singleton instance is STILL: " + Singleton. get_singleton())
The singleton pattern can also be implemented by making singleton classes use metaclasses ( Its type , Has a previously defined metaclass ) To achieve . According to need , Metaclass __call__()
Method to ensure that only one instance of a class can be created :
class SingletonMeta( type):
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
metaclass because it is best suited for this purpose.
"""
_instances = {}
def __call__( cls, * args, * * kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
"""
if cls not in cls. _instances:
instance = super(). __call__( * args, * * kwargs)
cls. _instances[ cls] = instance
return cls. _instances[ cls]
class Singleton( metaclass = SingletonMeta):
def some_business_logic( self):
"""
Finally, any singleton should define some business logic, which can be
executed on its instance.
"""
# ...
if __name__ == "__main__":
# The client code.
s1 = Singleton()
s2 = Singleton()
if id( s1) == id( s2):
print( "Singleton works, both variables contain the same instance.")
else:
print( "Singleton failed, variables contain different instances.")
advantage :
shortcoming :
background : 1、 It is necessar
There are some pain points whe