一.特色:java
①單例類只能有一個實例安全
②單例類必須本身本身建立本身的惟一實例spa
③單例類必須給全部其餘對象提供這一實例線程
二.實現方法:code
①餓漢式對象
public class Singleton1{ private Singleton1(); private static Singleton1 single=new Singleton1(); public static final Singleton1 getInstance(){ return single; } }
②懶漢式1(線程不安全)get
public class Singleton1{ private Singleton1(); private static Singleton1 single=null; public static Singleton1 getInstance(){ if(single==null){ single=new Singleton1(); } return single; } }
這種方法由於在getInstance方法中沒有添加線程鎖,全部當有多個線程同時訪問該方法時就會產生多個Singleton1實例。class
③懶漢式2(線程安全,可是效率不高,即加入線程鎖[線程鎖的地方會浪費時間,若能夠減小判斷線程鎖便可節約時間])效率
public class Singleton1{ private Singleton1(); private static Singleton1 single=null; public static synchronized Singleton1 getInstance(){ if(single==null){ single=new Singleton1(); } return single; } }
④懶漢式3(線程安全,效率也高,即雙重判斷)方法
public class Singleton1{ private Singleton1(); private static Singleton1 single=null; public static Singleton1 getInstance(){ if(single==null){ synchronized(Singleton1.class){ if(single==null){ s=new Singleton1(); } } } return single; } }