1、什麼是單例ide
一、私有的靜態全局變量,變量類型就是該類的類型。測試
二、構造方法私有化(避免使用new去建立對象)spa
三、對外提供公有的靜態方法,用於獲取該類對象。code
2、單例解決什麼問題對象
確保類對象的惟一性(即該類只能有一個對象)blog
3、單例的種類和代碼實現get
餓漢模式event
1 public class Singleton { 2 3 private static Singleton instance = null; //靜態全局變量
//private static Singleton instance = new Singleton();
4 5 /** 6 私有的構造方法 7 @param 無 8 */ 9 private Singleton(){ 10 11 } 12 13 //靜態初始化塊 14 static{ 15 instance = new Singleton(); 16 } 17 18 /** 19 靜態方法getInstance() 20 @param 無 21 */ 22 public static Singleton getInstance(){ 23 //懶漢模式 24 /*if(instance == null){ 25 instance= new Singleton(); 26 }*/ 27 return instance; 28 } 29 }
測試單例模式class
1 public class SingletonTest { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 8 //不能經過new來建立對象,由於構造方法私有 9 //Student s3= new Student(); 10 //調用Student類的靜態方法獲取對象的地址 11 Singleton s1= Singleton.getInstance(); 12 Singleton s2= Singleton.getInstance(); 13 /* 14 比較兩個變量的值是否相等若是相等,則代表只建立了一個對象, 15 兩個變量都共有該對象的地址 16 */ 17 System.out.println(s1 == s2); 18 } 19 20 }
升級版變量
1 public class Singleton1 { 2 3 private static final class SingletonHolder{ 4 private static final Singleton1 INSTANCE = new Singleton1(); 5 } 6 7 private Singleton1(){ 8 9 } 10 11 public static Singleton1 getInstance(){ 12 return SingletonHolder.INSTANCE; 13 } 14 }
反序列化版
1 public class Singleton2 implements Serializable{ 2 3 //防止建立多個對象 4 private static final class SingletonHolder{ 5 private static final Singleton2 INSTANCE = new Singleton2(); 6 } 7 8 private Singleton2(){ 9 10 } 11 12 public static Singleton2 getInstance(){ 13 return SingletonHolder.INSTANCE; 14 } 15 16 //反序列化 17 private Object readResolve(){ 18 return SingletonHolder.INSTANCE; 19 } 20 } 21 22 //枚舉實現單例 23 /* 24 public enumSingleton{ 25 INSTANCE; 26 public File openFile(String fileName){ 27 return getFile(fileName); 28 } 29 }*/
懶漢模式
1 public class Singleton3 { 2 3 private static volatile Singleton3 singleton3; 4 5 private Singleton3(){ 6 7 } 8 9 public static Singleton3 getInstance(){ 10 if(null == singleton3){ 11 synchronized (Singleton3.class) { 12 if(null == singleton3){ 13 singleton3 = new Singleton3(); 14 } 15 } 16 } 17 return singleton3; 18 } 19 20 }