//1 懶漢,線程不安全 public class Singleton { private static Singleton instance = null; private Singleton(){} public static Singleton getInstance(){ if(instan... ...
//1 懶漢,線程不安全 public class Singleton { private static Singleton instance = null; private Singleton(){} public static Singleton getInstance(){ if(instance == null ) { instance = new Singleton(); } return instance; } } //2 懶漢,線程安全 public class Singleton { private static Singleton instance = null; private Singleton(){} public static synchronized Singleton getInstance(){ if(instance == null ) { instance = new Singleton(); } return instance; } } //3 餓漢 public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } } //4 靜態內部類 public class Singleton { private static class SingletonHolder { public static Singleton instance = new Singleton(); } private Singleton(){} public static Singleton getInstance(){ return Singleton.SingletonHolder.instance; } } //5 枚舉 public class Singleton { private Singleton(){} public static Singleton getInstance(){ return Single.instance.getInstance(); } private static enum Single { instance; private Singleton single; //JVM會保證此方法絕對只調用一次 private Single(){ single = new Singleton(); } public Singleton getInstance(){ return single; } } } //6 雙重校驗鎖 public class Singleton { private static volatile Singleton instance = null; private Singleton(){} private static Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if(instance == null){ instance = new Singleton(); } } } return instance; } }