Android(java)学習ノート78:設計モードの単例モード
10736 ワード
パターンコードの例:
単例モードの餓漢式:
単例モードの怠け者式:
単例モードの餓漢式:
1 package cn.itcast_03;
2
3 public class Student {
4 // 5 private Student() { 6 } 7
8 //
9 // , 10 // , private
11 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); // false
16
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,cn.itcast_03.Student@175078b
26 System.out.println(s2);// null,cn.itcast_03.Student@175078b
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,t3
26 if (t == null) {// 27 //t1,t2,t3 28 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); // cn.itcast_03.Teacher@175078b
9 System.out.println(t2);// cn.itcast_03.Teacher@175078b
10 }
11 }