設計模式之單例式

1,餓漢式

public class Student {
	// 構造私有
	private Student() {
	}

	// 自己造一個
	// 靜態方法只能訪問靜態成員變量,加靜態
	// 爲了不讓外界直接訪問修改這個值,加private
	private static Student s = new Student();

	// 提供公共的訪問方式
	// 爲了保證外界能夠直接使用該方法,加靜態
	public static Student getStudent() {
		return s;
	}
}

 

 

/*
 * 單例模式:保證類在內存中只有一個對象。
 * 
 * 如何保證類在內存中只有一個對象呢?
 * 		A:把構造方法私有
 * 		B:在成員位置自己創建一個對象
 * 		C:通過一個公共的方法提供訪問
 */
public class StudentDemo {
	public static void main(String[] args) {
		// Student s1 = new Student();
		// Student s2 = new Student();
		// System.out.println(s1 == s2); // false

		// 通過單例如何得到對象呢?

		// Student.s = null;

		Student s1 = Student.getStudent();
		Student s2 = Student.getStudent();
		System.out.println(s1 == s2);

		System.out.println(s1); // null,cn.itcast_03.Student@175078b
		System.out.println(s2);// null,cn.itcast_03.Student@175078b
	}
}

2,餓漢式

/*
 * 單例模式:
 * 		餓漢式:類一加載就創建對象
 * 		懶漢式:用的時候,纔去創建對象
 * 
 * 面試題:單例模式的思想是什麼?請寫一個代碼體現。
 * 
 * 		開發:餓漢式(是不會出問題的單例模式)
 * 		面試:懶漢式(可能會出問題的單例模式)
 * 			A:懶加載(延遲加載)	
 * 			B:線程安全問題
 * 				a:是否多線程環境	是
 * 				b:是否有共享數據	是
 * 				c:是否有多條語句操作共享數據 	是
 */
public class Teacher {
	private Teacher() {
	}

	private static Teacher t = null;

	public synchronized static Teacher getTeacher() {
		// t1,t2,t3
		if (t == null) {
			//t1,t2,t3
			t = new Teacher();
		}
		return t;
	}
}
public class TeacherDemo {
	public static void main(String[] args) {
		Teacher t1 = Teacher.getTeacher();
		Teacher t2 = Teacher.getTeacher();
		System.out.println(t1 == t2);
		System.out.println(t1); // cn.itcast_03.Teacher@175078b
		System.out.println(t2);// cn.itcast_03.Teacher@175078b
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章