android 幾種單例模式的寫法
阿新 • • 發佈:2019-01-07
首先,先不論單例模式的寫法,有些方面是相同的,比如都需要將唯一的物件設定為static的,都需要將構造方法private化,程式碼如下:
public class MyInstance { private static MyInstance instance; private MyInstance(){}
}
第一種:最原始的單例模式,程式碼如下:
public static MyInstance getInstance(){ if(instance==null){ instance=new MyInstance(); } returninstance; }
多執行緒併發時,可能會出現重複new物件的情況,因此不提倡使用。
第二種:將整個方法塊進行加鎖,保證執行緒安全。public static synchronized MyInstance getInstance(){ if(instance==null){ instance=new MyInstance(); } return instance; }這種程式碼下,每條執行緒都會依次進入方法塊內部,雖然實現了單例,但是影響了執行效率,可以使用但是也不怎麼提倡。
第三種:進一步優化的方法。
public static MyInstance getsInstance(){ synchronized (MyInstance.class){ if(instance==null){ instance=new MyInstance(); return instance; }else{ return instance; } } }這種方式只是第二種方法的一種優化,但是優化有限。
以下的幾種方法比較推薦大家使用:
第四種:雙層判斷加鎖,效率影響小且保證了執行緒安全。
public static MyInstance getsInstance() { if (instance == null) { synchronized (MyInstance.class) { if(instance==null){ instance=new MyInstance(); } } } return instance; }這種方法是在觀看閆振杰大神的直播時看到的,頓時感覺相當棒,是對第二種和第三種方法的進一步優化,比較推薦大家使用。
第五種:內部類實現單例,不用執行緒鎖來實現效率的提升。
public class MyInstance { private MyInstance() { } public static MyInstance getInstance(){ return MyInstanceHolder.instance; } private static class MyInstanceHolder{ private static MyInstance instance=new MyInstance(); } }在內部類中new物件,再將內部類的物件返回,這種方法是使用了java中class載入時互斥的原理來實現了執行緒的安全。不加執行緒鎖也使得執行效率不會受到較大的影響。比較提倡。