標籤:
單例模式程式碼範例:
單例模式之餓漢式:
1 package cn.itcast_03; 2 3 public class Student { 4 // 構造私人 5 private Student() { 6 } 7 8 // 自己造一個 9 // 靜態方法只能訪問靜態成員變數,加靜態10 // 為了不讓外界直接存取修改這個值,加private11 private static Student s = new Student();12 13 // 提供公用的訪問方式14 // 為了保證外界能夠直接使用該方法,加靜態,不加static,外界就必須建立一個對象,顯然這裡是不容許的15 public static Student getStudent() {16 return s;//這裡是原子性操作,不是多條語句操作共用資料,所以開發的時候,我們用餓漢式,會比較安全(開發時候會常涉及到多線程)17 }18 }
1 package cn.itcast_03; 2 3 /* 4 * 單例模式:保證類在記憶體中只有一個對象。 5 * 6 * 如何保證類在記憶體中只有一個對象呢? 7 * A:把構造方法私人 8 * B:在成員位置自己建立一個對象 9 * C:通過一個公用的方法提供訪問10 */11 public class StudentDemo {12 public static void main(String[] args) {13 // Student s1 = new Student();14 // Student s2 = new Student();15 // System.out.println(s1 == s2); // false16 17 // 通過單例如何得到對象呢?18 19 // Student.s = null;20 21 Student s1 = Student.getStudent();22 Student s2 = Student.getStudent();23 System.out.println(s1 == s2);24 25 System.out.println(s1); // null,[email protected]26 System.out.println(s2);// null,[email protected]27 }28 }
單例模式之懶漢式:
1 package cn.itcast_03; 2 3 /* 4 * 單例模式: 5 * 餓漢式:類一載入就建立對象 6 * 懶漢式:用的時候,才去建立對象 7 * 8 * 面試題:單例模式的思想是什麼?請寫一個代碼體現。 9 * 10 * 開發:餓漢式(是不會出問題的單例模式)11 * 面試:懶漢式(可能會出問題的單例模式)12 * A:懶載入(消極式載入) 13 * B:安全執行緒問題14 * a:是否多線程環境 是15 * b:是否有共用資料 是16 * c:是否有多條語句操作共用資料 是17 */18 public class Teacher {19 private Teacher() {20 }21 22 private static Teacher t = null;23 24 public synchronized static Teacher getTeacher() {25 // t1,t2,t326 if (t == null) {//多條語句操作共用資料27 //t1,t2,t328 t = new Teacher();29 }30 return t;31 }32 }
1 package cn.itcast_03; 2 3 public class TeacherDemo { 4 public static void main(String[] args) { 5 Teacher t1 = Teacher.getTeacher(); 6 Teacher t2 = Teacher.getTeacher(); 7 System.out.println(t1 == t2); 8 System.out.println(t1); // [email protected] 9 System.out.println(t2);// [email protected]10 }11 }
Android(java)學習筆記78:設計模式之單例模式