JAVA-单例模式的几种实现方式
?
一、什么是單例模式
????
????單例:保證一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)訪問(wèn)它的全局訪問(wèn)點(diǎn)。
????單例模式是一種常用的軟件設(shè)計(jì)模式之一,其目的是保證整個(gè)應(yīng)用中只存在類的唯一個(gè)實(shí)例。
????比如我們?cè)谙到y(tǒng)啟動(dòng)時(shí),需要加載一些公共的配置信息,對(duì)整個(gè)應(yīng)用程序的整個(gè)生命周期中都可見(jiàn)且唯一,這時(shí)需要設(shè)計(jì)成單例模式。如:spring容器,session工廠,緩存,數(shù)據(jù)庫(kù)連接池等等。
?
二、如何保證實(shí)例的唯一
? ? ? ? ?1)防止外部初始化
? 2)由類本身進(jìn)行實(shí)例化
? 3)保證實(shí)例化一次
? 4)對(duì)外提供獲取實(shí)例的方法
? 5)線程安全
三、幾種單利模式的比較
?
(1)餓漢式
“因?yàn)轲I,所以要立即吃飯,刻不容緩”,在定義類的靜態(tài)私有變量同時(shí)進(jìn)行實(shí)例化。
public class Singleton {private static final Singleton singleton = new Singleton();private Singleton() {}public static Singleton getInstance() {return singleton;}}①聲明靜態(tài)私有類變量,且立即實(shí)例化,保證實(shí)例化一次
②私有構(gòu)造,防止外部實(shí)例化(通過(guò)反射是可以實(shí)例化的,不考慮此種情況)
③提供public的getInstance()方法供外部獲取單例實(shí)例
好處:線程安全;獲取實(shí)例速度快 缺點(diǎn):類加載即初始化實(shí)例,內(nèi)存浪費(fèi)。
?
2)懶漢式
“這個(gè)人比較懶,等用著你的時(shí)候才去實(shí)例化”,延遲加載。
public class Singleton {
private static Singleton singleton = null;
public class Singleton {private static Singleton singleton = null;private Singleton() {}public static Singleton getInstance() {if (singleton == null) {singleton = new Singleton();}return singleton;}}優(yōu)點(diǎn):在獲取實(shí)例的方法中,進(jìn)行實(shí)例的初始化,節(jié)省系統(tǒng)資源
缺點(diǎn):①如果獲取實(shí)例時(shí),初始化工作較多,加載速度會(huì)變慢,影響系統(tǒng)系能
②每次獲取實(shí)例都要進(jìn)行非空檢查,系統(tǒng)開(kāi)銷大
③非線程安全,當(dāng)多個(gè)線程同時(shí)訪問(wèn)getInstance()時(shí),可能會(huì)產(chǎn)生多個(gè)實(shí)例。
?
接下來(lái)對(duì)上述例子進(jìn)行線程安全改造:
(1)同步鎖:
public class Singleton {private static Singleton singleton = null;private Singleton() {}public synchronized static Singleton getInstance() {if (singleton == null) {singleton = new Singleton();}return singleton;}}優(yōu)點(diǎn):線程安全,缺點(diǎn):每次獲取實(shí)例都要加鎖,耗費(fèi)資源,其實(shí)只要實(shí)例已經(jīng)生成,以后獲取就不需要再鎖了。
(2)雙重檢查鎖:
public class Singleton {private static Singleton singleton = null;private Singleton() {}public static Singleton getInstance() {if (singleton == null) {synchronized (Singleton.class) {if (singleton == null) {singleton = new Singleton();}}}return singleton;}}優(yōu)點(diǎn):線程安全,進(jìn)行雙重檢查,保證只在實(shí)例未初始化前進(jìn)行同步,效率高 缺點(diǎn):還是實(shí)例非空判斷,耗費(fèi)一定資源。
(3)靜態(tài)內(nèi)部類:
public class Singleton {private Singleton() {}private static class SingletonHolder {private static final Singleton singleton = new Singleton();}public static Singleton getInstance() {return SingletonHolder.singleton;}}優(yōu)點(diǎn):既避免了同步帶來(lái)的性能損耗,又能夠延遲加載。
(4)枚舉:
public enum Singleton {INSTANCE;public void init() {System.out.println("資源初始化");} }天然線程安全,可防止反射生成實(shí)例。
?
四、單例模式的優(yōu)缺點(diǎn):
優(yōu)點(diǎn):該類只存在一個(gè)實(shí)例,節(jié)省系統(tǒng)資源;對(duì)于需要頻繁創(chuàng)建銷毀的對(duì)象,使用單例模式可以提高系統(tǒng)性能。?
缺點(diǎn):不能外部實(shí)例化(new),調(diào)用人員不清楚調(diào)用哪個(gè)方法獲取實(shí)例時(shí)會(huì)感到迷惑,尤其當(dāng)看不到源代碼時(shí)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/cat520/p/11259400.html
總結(jié)
以上是生活随笔為你收集整理的JAVA-单例模式的几种实现方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CGI,BOA配置心得
- 下一篇: 二分查找(模板)