單例模式

單例模式

1.定義

????????單例也叫單態(tài)模式, 是設(shè)計(jì)模式中最簡(jiǎn)單的一種。當(dāng)一個(gè)類被創(chuàng)建之后, 只能產(chǎn)生一個(gè)實(shí)例供外部訪問, 并且提供一個(gè)全局訪問的方法。

? ? ? ? 單例的最終目的就是保證一個(gè)類在內(nèi)存中只能有一個(gè)實(shí)例(對(duì)象)。

? ? ? ? Java中頻繁創(chuàng)建和銷毀類對(duì)象都會(huì)占用一部風(fēng)系統(tǒng)資源,使用單例模式可以提高性能。

? ? ? ? 單例模式創(chuàng)建的對(duì)象不會(huì)被回收,過多的單例照成內(nèi)存溢出。

2.創(chuàng)建過程

? ? ? ? 私有化構(gòu)造方法(使用private修飾)

? ? ? ? 在其內(nèi)部產(chǎn)生該類的實(shí)例化對(duì)象,并將其封裝成private static 類型

? ? ? ? 定義一個(gè)靜態(tài)的方法返回該類的實(shí)例

3.餓漢式和懶漢式

餓漢式

public class Singleton{

? ? private static Singleton singleton = new Singleton();

? ? private Singleton(){}

? ? public static Singleton getInstance(){

????????return singleton;

????}

}

懶漢式

public class Singleton{

? ? private static Singleton singleton;

? ? private Singleton(){}

? ? public static Singleton getInstance(){

? ? if(singleton==null){

? ? ? ? singleton = new Singleton();

????????}

? ? ? ? return singleton;

????}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容