In depth explanation of single piece mode of Java design pattern
- 2021-12-11 17:41:50
- OfStack
Definition
One-piece mode ensures that one class has only one instance and provides one global access point
Java singleton mode
Implementation of Classical One-piece Pattern
public class Singleton{
private static Singleton uniqueInstance; // Utilization 1 Static variables to record Singleton Uniqueness of class 1 Instances
private Singleton(){} // Declare the constructor private, only from the Singleton You can call the constructor only within the class
// Use getInstance() Method instantiates the object and returns this instance
public static Singleton getInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
The above code will generate multiple instances in multithreading, so we need to improve the code
Implementation of multithreading single-piece mode
public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
By adding the synchronized keyword to the getInstance () method, we force each thread to wait for another thread to leave the method before entering it. That is, no two threads can enter this method at the same time.
Eager to create an instance
public class Singleton{
// In the static initializer ( static initializai ). This ensures thread safety ( thread sate )
private static Singleton uniqueInstance = new Singleton();
private static Singleton getInstance(){
return uniqueInstance;
}
}
When JVM loads this class, it immediately creates this one-piece instance. JVM guarantees that this instance will be created before any thread accesses the uniqueInstance static variable.
Double check locking
There are two checks for the existence of the instance, if it does not exist, it is created, and if it exists, it returns
public class Singlenton{
// volatile Key words: when uniqueInstance Variable is initialized to Singleton Instance, multiple threads correctly handle the uniqueInstance Variable
private volatile static Singleton uniqueInstance();
private Singleton(){}
public static Singleton getInstance(){
// Check the instance, and if it does not exist, enter the synchronization block
if(uniqueInstance == null){
// After entering the block, check again 1 Times. If it is still null To create an instance
synchronized (Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
Python singleton mode
Module implementation
The module of Python is a natural one-piece mode. When the module is imported for the first time, the. pyc file will be generated. When the module is imported again, the previously generated. pyc file will be directly loaded, and the module code will not be executed again
Create an Singleton file first
class Singleton:
def getSingleton:
pass
singleton = Singleton()
Import this module in another file. The address of this class is only 1
Implementation of new Keyword
When an object is instantiated, the __new__ method of the class is called first, and the parent class Object.__new__ method is called by default to instantiate the object. Then call the __init__ method of the class to initialize the property.
We can add a judgment to the __new__ method. If the instance exists, it will not be instantiated, and if it does not exist, it will be instantiated.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
pass
Decorator implementation
Implement single-piece mode through decorator
Function decorator
def singleton(cls):
# Create 1 A private variable of type dictionary, which is used to store the class address
_instance = {}
def inner():
# If the class does not exist
if cls not in _instance:
# Instantiation 1 Classes and stored in the dictionary
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class ClassName(object):
def __init__(self):
pass
Class decorator
class Singleton(object):
def __init__(self, cls):
self._cls = cls # Accept class name
self._instance = {} # Store class address
def __call__(self):
if self._cls not in self._instance:
# Instantiate a class and store it in a dictionary
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton
class ClassName(object):
def __init__(self):
pass
The above is the Java Design Pattern Single Piece Pattern in-depth explanation of the details, more information about the Java Design Pattern please pay attention to other related articles on this site!