回顧基礎(chǔ)知識(shí),溫故而知新。
單例模式有餓漢模式和懶漢模式

1 package com.xiaoysec.designpattern; 2 /** 3 * 4 * @author xiaoysec 5 *本例是展示java單例模式中的餓漢模式 6 *餓漢模式 特點(diǎn): 類(lèi)加載的速度比較慢(在類(lèi)加載的過(guò)程中創(chuàng)建唯一的實(shí)例對(duì)象) 運(yùn)行的速度會(huì)比較快 線程安全 7 */ 8 9 public class Singleton {10 //將構(gòu)造方法定義為私有 防止外部創(chuàng)建新的實(shí)例對(duì)象11 PRivate Singleton(){}12 13 //private static修飾 在類(lèi)加載時(shí)就創(chuàng)建唯一的實(shí)例對(duì)象 14 private static Singleton instance = new Singleton();15 16 //public static修飾 外部調(diào)用以獲取實(shí)例對(duì)象的引用17 public static Singleton getInstance(){18 return instance;19 }20 public static void main(String[] args){21 Singleton instance = Singleton.getInstance();22 Singleton instance2 = Singleton.getInstance();23 if(instance == instance2){24 System.out.println("是相同的對(duì)象");25 }26 else27 System.out.println("不是相同的對(duì)象");28 }29 30 }View Code

1 package com.xiaoysec.designpattern; 2 /** 3 * 4 * @author xiaoysec 5 *本例主要展示java單例模式中的懶漢模式 6 *懶漢模式的特點(diǎn)是 在類(lèi)加載是并不創(chuàng)建實(shí)例對(duì)象 類(lèi)加載的速度比較快但是運(yùn)行的速度會(huì)比較慢(對(duì)象創(chuàng)建)線程不安全 7 */ 8 public class Singleton2 { 9 private Singleton2(){}10 11 12 private static Singleton2 instance = null;13 14 15 public static Singleton2 getInstance(){16 if(instance==null){17 instance = new Singleton2();18 }19 return instance;20 }21 public static void main(String[] args){22 Singleton2 instance1 = Singleton2.getInstance();23 Singleton2 instance2 = Singleton2.getInstance();24 if(instance1 == instance2){25 System.out.println("是同一個(gè)對(duì)象");26 }else27 System.out.println("不是同一個(gè)對(duì)象");28 }29 30 }View Code新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注