国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

單例模式--確保一個(gè)類(lèi)只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)。

2019-11-11 06:14:15
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

一、定義:單件模式--確保一個(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;	}	}


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吉水县| 龙里县| 陕西省| 香格里拉县| 平泉县| 渭源县| 淮北市| 东乌珠穆沁旗| 金寨县| 甘泉县| 乾安县| 茌平县| 门源| 鹤岗市| 宁城县| 突泉县| 富顺县| 冀州市| 溆浦县| 汕头市| 绵竹市| 英吉沙县| 温宿县| 蕉岭县| 景宁| 金沙县| 固镇县| 万载县| 阳谷县| 边坝县| 手游| 屯留县| 安泽县| 讷河市| 尚义县| 咸丰县| 北辰区| 长春市| 河西区| 五常市| 锡林郭勒盟|