The singleton pattern is a creative design pattern. When we write programs and encounter a class that needs to be used frequently in global applications and the analogy is large, we can consider using the singleton pattern to design to reduce GC pressure and improve response speed. For example, thread pools, database connection pools, and so on can be designed using singletons. Spring’s IOC, for example, also uses the singleton pattern.
There are several key points in the design of the singleton pattern
- Constructors are not open to the public and are generally private
- Return the instance through a static method
- Ensure that there is one and only one instance of a class, especially in a multithreaded environment
- Try to be thread-safe
The hungry type
/** ** create instance initialization in memory ** use class loading mechanism to avoid multi-thread safety */
public class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton(a){}
private static Singleton getInstance(a){
returnsingleton; }}Copy the code
LanHanShi
/** * Synchronized is a synchronized approach to creating objects */
public class Singleton {
private static Singleton singleton = null;
private Singleton(a){}
private static synchronized Singleton getInstance(a){
if(singleton == null){
singleton = new Singleton();
}
returnsingleton; }}Copy the code
Static inner class
public class Singleton {
private static class Holder{
private static final Singleton instance = new Singleton();
}
private Singleton(a){}
private static Singleton getInstance(a){
returnHolder.instance; }}Copy the code
Double lock DCL
public class Singleton {
private Singleton(a) {}
private volatile static Singleton singleton = null;
public static Singleton getInstance(a) {
if (singleton == null) {
synchronized (Singleton.class){
if(singleton == null){
singleton = newSingleton(); }}}returnsingleton; }}Copy the code