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

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

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

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

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

二、方式:

1.懶漢式

/** *  * @author Kevintan * 經(jīng)典的單件模式的實(shí)現(xiàn),懶漢式 * synchronized 處理多線(xiàn)程的同步問(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ā)表
主站蜘蛛池模板: 平顶山市| 桦南县| 岳普湖县| 寿光市| 大田县| 杭锦旗| 望奎县| 清原| 保康县| 阳城县| 无为县| 遂宁市| 大兴区| 海兴县| 固阳县| 贵德县| 临桂县| 五大连池市| 广东省| 乌海市| 长汀县| 和林格尔县| 安国市| 米脂县| 富裕县| 九寨沟县| 樟树市| 富顺县| 射阳县| 新乡市| 莱阳市| 鄄城县| 延川县| 平乐县| 辽源市| 靖边县| 沙田区| 包头市| 天台县| 五莲县| 云南省|