一、定義:單件模式--確保一個(gè)類(lèi)只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)。
二、方式:
1.懶漢式
/** * * @author Kevintan * 經(jīng)典的單件模式的實(shí)現(xiàn),懶漢式 * synchronized 處理多線程的同步問(wèn)題。 * 缺點(diǎn):降低了性能,不利于程序頻繁的調(diào)用 * 適用場(chǎng)景:性能對(duì)應(yīng)用程序不是很關(guān)鍵。 */public class Singleton1 { PRivate static Singleton1 uniqueInstance ; private Singleton1() {} public static synchronized Singleton1 getInstance(){ if (uniqueInstance == null) { uniqueInstance = new Singleton1(); } return uniqueInstance; } }2.餓漢式/** * * @author Kevintan * 急切實(shí)例化,餓漢式 * 適用于:應(yīng)用程序總是創(chuàng)建并使用單件實(shí)例或創(chuàng)建和運(yùn)行時(shí)的負(fù)擔(dān)不太繁重。 * 缺點(diǎn):不能用于頻繁創(chuàng)建或使用或耗費(fèi)內(nèi)存過(guò)大的程序中。 */public class Singleton2 { private static Singleton2 uniqueInstance = new Singleton2(); private Singleton2() {} public static Singleton2 getInstance(){ if (uniqueInstance == null) { uniqueInstance = new Singleton2(); } return uniqueInstance; } }3.雙重檢索加鎖/** * * @author Kevintan *雙重檢索加鎖 *原理:首先檢查是否實(shí)例已經(jīng)創(chuàng)建了,如果尚未創(chuàng)建,“才”進(jìn)行同步。 *這樣一來(lái),只有第一次創(chuàng)建實(shí)例時(shí)會(huì)同步。 *優(yōu)點(diǎn)及適用于:幫助你大大減少時(shí)間耗費(fèi),提高性能 */public class Singleton3 { private static volatile Singleton3 uniqueInstance ; private Singleton3() {} public static synchronized Singleton3 getInstance(){ if (uniqueInstance == null) { synchronized (Singleton3.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton3(); } } } return uniqueInstance; } }
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注