Java中设计模式之单例设计模式-1
生活随笔
收集整理的這篇文章主要介紹了
Java中设计模式之单例设计模式-1
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
單例作用
- 1 節(jié)省內(nèi)存
- 2 可以避免多種狀態(tài)導(dǎo)致?tīng)顟B(tài)沖突
單例的創(chuàng)建步驟
- 1 私有化構(gòu)造方法
- 2 私有化聲明的屬性
- 3 getInstance
- 4 方法需要靜態(tài)
單例分類
1.懶漢式
2.餓漢式
兩種單例區(qū)別:
餓漢式 線程安全的
懶漢式 線程不安全的
餓漢式:
package 設(shè)計(jì)模式之單例; //餓漢式: public class HungeryMode {private final static HungeryMode INSTANCE=new HungeryMode();public static HungeryMode getInstance() {return INSTANCE;}private HungeryMode(){}}懶漢式:
package 設(shè)計(jì)模式之單例;public class LazyMode {private static LazyMode instance=null;public static LazyMode getInstance() {if(instance==null){instance=new LazyMode();}return instance;}private LazyMode(){} }測(cè)試:
package 設(shè)計(jì)模式之單例;public class Test1 {public static void main(String[] args){//餓漢式 HungeryMode instance=HungeryMode.getInstance();HungeryMode instance2=HungeryMode.getInstance();System.out.println("instance="+instance);System.out.println("instance2="+instance2);// 懶漢式LazyMode instance3=LazyMode.getInstance();LazyMode instance4=LazyMode.getInstance();LazyMode instance5=LazyMode.getInstance();System.out.println("instance3="+instance3+","+instance3.hashCode());System.out.println("instance4="+instance4+","+instance4.hashCode());System.out.println("instance5="+instance5+","+instance5.hashCode());} }測(cè)試結(jié)果:
創(chuàng)建多個(gè)對(duì)象,測(cè)試內(nèi)存地址,如果相同說(shuō)明創(chuàng)建的是同一個(gè)對(duì)象,說(shuō)明創(chuàng)建的是單例!
延伸—————————–懶漢式線程安全性處理————————–
懶漢式線程不安全原因:
在多線程中,創(chuàng)建單例時(shí),可能出現(xiàn)多個(gè)線程進(jìn)入if(instance==null)執(zhí)行語(yǔ)句中,在一個(gè)線程創(chuàng)建了一個(gè)instance后,其他進(jìn)入執(zhí)行語(yǔ)句的線程也會(huì)接著創(chuàng)建,這樣就會(huì)產(chǎn)生多個(gè)對(duì)象,實(shí)現(xiàn)不了單例了,此時(shí)不安全了。
代碼:
package 設(shè)計(jì)模式之單例;public class LazyMode2 {private static LazyMode2 instance=null;private LazyMode2(){}public static LazyMode2 getInstance(){// 雙重檢查if(instance==null){// 為了提高效率 盡可能少的讓線程反復(fù)判斷鎖synchronized (LazyMode2.class) {// 靜態(tài)方法中 不能使用this 就可以用 本類.class 來(lái)代替if(instance==null){instance=new LazyMode2();}}}return instance;} }總結(jié)
以上是生活随笔為你收集整理的Java中设计模式之单例设计模式-1的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java中File类应用:遍历文件夹下所
- 下一篇: Java中设计模式之装饰者模式-2