回顧基礎知識,溫故而知新。
單例模式有餓漢模式和懶漢模式
1 package com.xiaoysec.designpattern; 2 /** 3 * 4 * @author xiaoysec 5 *本例是展示java單例模式中的餓漢模式 6 *餓漢模式 特點: 類加載的速度比較慢(在類加載的過程中創建唯一的實例對象) 運行的速度會比較快 線程安全 7 */ 8 9 public class Singleton {10 //將構造方法定義為私有 防止外部創建新的實例對象11 PRivate Singleton(){}12 13 //private static修飾 在類加載時就創建唯一的實例對象 14 private static Singleton instance = new Singleton();15 16 //public static修飾 外部調用以獲取實例對象的引用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("是相同的對象");25 }26 else27 System.out.println("不是相同的對象");28 }29 30 }View Code
1 package com.xiaoysec.designpattern; 2 /** 3 * 4 * @author xiaoysec 5 *本例主要展示java單例模式中的懶漢模式 6 *懶漢模式的特點是 在類加載是并不創建實例對象 類加載的速度比較快但是運行的速度會比較慢(對象創建)線程不安全 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("是同一個對象");26 }else27 System.out.println("不是同一個對象");28 }29 30 }View Code
新聞熱點
疑難解答