Thrust
Ensure that there is at most one instance of a type for the entire program life cycle
Applicable scenarios
A system can create multiple print tasks, but only one print task is supported at the same time
Characteristics
1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
Classification
The common singleton pattern is divided into two kinds of a hungry man and lazy type.
1. A Hungry man mode
public class singleton{
private static Singleton _instance=new Singleton ();
Private Singleton () {};
public static Singleton getinstance () {
return _instance;
}
}
Since the JVM created the Singleton class and also created a static singleton instance, the pattern is inherently thread-safe
2. Lazy mode (double check lock)
public class singleton{
private static Singleton _instance;
Private Singleton () {}
Public Singleton getinstance () {
if (_instance==null) {
Synchronized (Singleton.class) {
if (_instance==null) {
_instance=new Singleton ();
}
}
}
return _instance;
}
}
Because of this pattern in order to ensure thread-safe use of synchronized efficiency is reduced, but also before the use of synchronized a layer of judgment, a certain level of shielding synchronized execution
3. Lazy mode (Static inner Class)
public class Singleton {
private Static Class Lazyloader {
Private static final Singleton instance = new Singleton ();
}
Private Singleton () {
}
public static Singleton getinstance () {
return lazyloader.instance;
}
}
Because the instance member of the static inner class Lazyloader is instantiated only when it is first called
Design Patterns--single case