Single example implementation I
A very simple implementation
public class Singleton {
public static Singleton instance = new Singleton();
private Singleton() {
System.out.println("Singleton is create");
}
public static Singleton getSingleton() {
return instance;
}
}
One disadvantage of this approach is that when Singleton objects are created is not controlled. For static member instance, it is created when the class is first initialized, which is not necessarily the first time getSingleton() is called.
extend
For example, such a singleton object:
public class Singleton {
public static int STATUS = 1;
public static Singleton instance = new Singleton();
private Singleton() {
System.out.println("Singleton is create");
}
public static Singleton getSingleton() {
return instance;
}
}
Referencing STATUS anywhere will cause the class to be initialized and instance to be created.
Single example implementation II
If you want to precisely control the creation time of an instance, look for a strategy that supports delayed loading.
public class LazySingleton {
public static LazySingleton instance = null;
private LazySingleton() {
System.out.println("LazySingleton is create");
}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
To prevent objects from being created multiple times, synchronize them with synchronized.
Single example implementation 3
In the above two single case models, each has its own merits. The following implementation can combine the two advantages.
public class StaticSingleton {
private StaticSingleton() {
System.out.println("StaticSingleton is create");
}
private static class SingletonHolder {
private static StaticSingleton instance = new StaticSingleton();
}
public static StaticSingleton getInstance() {
return SingletonHolder.instance;
}
}
First of all, getInstance () method has no lock, so it has excellent performance in high concurrency environment. Second, the StaticSingleton instance is created only when getInstance() is first called. Smart use of internal class and class initialization mechanism.
duplication check
There is also a dual check mode. "But it's ugly, complicated, and sometimes it doesn't guarantee it's right." Double check lock and delay initialization errors
Invariant pattern
A detailed explanation of invariant patterns in Java multithreaded programming