Peb siv singleton chav kawm nyob qhov twg hauv Java?
Peb siv singleton chav kawm nyob qhov twg hauv Java?

Video: Peb siv singleton chav kawm nyob qhov twg hauv Java?

Video: Peb siv singleton chav kawm nyob qhov twg hauv Java?
Video: qhia peb siv lub koob thaij thiab saib seb yuav thaij tau zoo npaum li cas 2024, Kaum ib hlis
Anonim

A ib leeg tsuas yog ib chav kawm uas yog instantiated raws nraim ib zaug nyob rau hauv lub Java Tshuab Virtual. Nws yog siv los muab lub ntiaj teb point ntawm kev nkag mus rau cov khoom. Nyob rau hauv cov nqe lus ntawm kev siv siv Singleton cov qauv yog siv hauv kev nkag, caches, xov pas dej, configuration settings, ntaus ntawv tsav tsheb khoom.

Yog li ntawd, qhov twg yog chav kawm singleton siv?

Cov chav kawm Singleton yog siv rau kev txiav, cov khoom tsav tsheb, caching thiab xov pas dej ua ke, database kev sib txuas. Ib qho kev siv ntawm singleton chav kawm yuav tsum muaj cov khoom nram qab no: Nws yuav tsum muaj ib qho piv txwv xwb: Qhov no yog ua los ntawm kev muab ib qho piv txwv ntawm chav kawm los ntawm sab hauv chav kawm.

Tom qab, lo lus nug yog, Singleton chav kawm ua haujlwm li cas? A ib leeg yog a chav kawm uas tso cai tsuas yog ib qho piv txwv ntawm nws tus kheej los tsim thiab muab nkag mus rau qhov tsim qauv ntawd. Nws muaj cov hloov pauv zoo li qub uas tuaj yeem ua raws li qhov tshwj xeeb thiab tus kheej ntawm nws tus kheej. Nws yog siv nyob rau hauv scenarios thaum tus neeg siv xav kom txwv instantiation ntawm ib chav kawm rau ib yam khoom xwb.

Tom qab ntawd, lo lus nug yog, dab tsi yog chav kawm singleton hauv Java thiab peb tuaj yeem ua ib chav kawm singleton li cas?

Singleton chav kawm txhais tau tias koj tuaj yeem tsim ib qho xwb khoom rau cov chav kawm. Koj tuaj yeem tsim ib chav kawm singleton los ntawm kev ua nws tus neeg tsim khoom ua tus kheej, kom koj tuaj yeem txwv qhov kev tsim ntawm qhov khoom . Muab ib txoj kev zoo li qub kom tau txais piv txwv ntawm cov khoom , nyob rau hauv uas koj tuaj yeem tuav cov khoom creation nyob rau hauv chav kawm nkaus xwb.

Muaj pes tsawg txoj hauv kev tsim ib chav kawm singleton hauv Java?

Hauv tsab ntawv no, kuv yuav piav qhia tsib txoj kev los siv cov Singleton qauv hauv Java . Lawv yog Synchronization tus getInstane() txoj kev, zoo li qub qhov kawg hloov pauv, siv ob chav kuaj ntsuas ntsuas nrog cov ntsiab lus tsis hloov pauv, siv SingletonHolder, thiab Enum.

Pom zoo: