一、//Synchronize the method public class Singleton {
private static Singleton uniqueInstantce;
private Singleton() { }
public static synchronized Singleton getInstance() { if (uniqueInstantce == null) { uniqueInstantce = new Singleton(); } return uniqueInstantce; } }
会大大降低程序的性能
二、//Use eager instantiation public class Singleton2 {
private static Singleton2 uniqueInstantce = new Singleton2();
private Singleton2() { }
public static Singleton2 getInstance() { return uniqueInstantce; } }
三、//Double-checked locking public class Singleton3 {
private volatile static Singleton3 uniqueInstantce;
private Singleton3() { }
public static Singleton3 getInstance() { if (uniqueInstantce == null) { synchronized (Singleton3.class) { if (uniqueInstantce == null) { uniqueInstantce = new Singleton3(); } } } return uniqueInstantce; } }