Java implements Singleton pattern
The Singleton pattern is a creative design pattern, which aims to ensure that there is only one instance of a class and provide a global access point.
Applicable scenario:
1. When it is necessary to ensure that there is only one instance of a class in the system, the Singleton pattern can be used. For example, database Connection pool, Thread pool and other shared resources.
2. When you need to instantiate an object frequently, you can use the Singleton pattern to improve performance. Because the Singleton pattern can only create one instance, multiple calls will not repeat the creation.
Benefits:
1. Singleton pattern can reduce memory expenditure because it only creates one instance and reduces the generation of objects.
2. The Singleton pattern can avoid multiple occupation of resources, such as Thread pool, database Connection pool, etc.
3. The Singleton pattern can provide a global access point in the whole system to facilitate the operation of instances.
The following is the complete sample code for implementing the Singleton pattern in Java:
public class Singleton {
//Privatizing constructors to prevent external instantiation of objects
private Singleton() {
}
//Create a static private instance
private static Singleton instance;
//Provide global access points to obtain singleton instances
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
In the above code, the constructor of the Singleton class is privatized, ensuring that other classes cannot create Singleton instances through the new keyword. The getInstance method can obtain a unique instance of Singleton. If the instance is empty, it is created through double check locking. Double check locking is to ensure normal operation in a multithreaded environment.