Basic definition
The singleton pattern is to ensure that there is only one instance of a certain class and provide a global access point. The singleton pattern has the following characteristics:
- It has only one instance.
- It must be instantiated on its own.
- It must provide access points to the entire system by itself.
Code
Hungry
Directly initialize static variables. This ensures thread safety.
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return singleton; } }
Lazy
Load on demand. Handle with synchronized. In other words, turn the getInstance () method into a synchronous method
public class LazySingleton { private static volatile LazySingleton lazySingleton; private LazySingleton(){ } public static LazySingleton getInstance(){ if(lazySingleton == null){ synchronized(LazySingleton.class){ lazySingleton = new LazySingleton(); } } return lazySingleton; } }
advantage
Saved system resources. Because there is only one instance object in the system, for some systems that need to frequently create and destroy objects, the singleton mode undoubtedly saves system resources and improves system performance.
Because the singleton class encapsulates its only instance, it can strictly control how and when customers access it.
Disadvantages
Because there is no abstraction layer in the singleton pattern, it is very difficult to expand the singleton class.
JDK source code
Lazy
java.lang.Runtim
Hungry
java.lang.System