核心原理
單例模式的核心原理是將構(gòu)造函數(shù)私有化拢驾, 并且提供一個(gè)static 的getInstance()方法獲取一個(gè)static的單例對(duì)象.
應(yīng)用場(chǎng)景
有些類會(huì)持有很多資源孽鸡, 比如ImageLoader類就會(huì)創(chuàng)建自己的線程池, 調(diào)用網(wǎng)絡(luò)API等道伟, 為了避免這些資源在進(jìn)程中被創(chuàng)建多份, 影響整體性能. 一般對(duì)于ImageLoader這樣的類來(lái)說帚豪, 都要去使用單例模式.
還有就是像設(shè)置類, 比如BrowserSettings.java紫皇, 對(duì)這個(gè)類來(lái)說, 是沒有必要?jiǎng)?chuàng)建多個(gè)它的對(duì)象出來(lái), 因此也最好使用單例模式.
最常用的實(shí)現(xiàn)方式
實(shí)現(xiàn)單例有幾種常用的方法, 但項(xiàng)目中最常用的標(biāo)準(zhǔn)方法是使用DCL(Double Check Lock)的方式實(shí)現(xiàn).
public class Singleton {
private static Singleton _instance;
private Singleton() {
}
public static Singleton getInstance() {
if(_instance == null) {
synchronized(Singleton.class) {
If(_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
}
其他的幾種實(shí)現(xiàn)方式了解一下就行了, 自己寫項(xiàng)目時(shí)盆耽, 只要記住用DCL的方式寫代碼就可以了.
---DONE.------