單例設計模式(餓漢式,懶漢式(1,有執行緒安全問題,2,安全高效))
package cn.itcast.mobilesafexian2.test;
public class Student {
/* (1)單例模式(只需建立一個物件) (外界訪問直接Student.getStudent 即可獲得物件 )
-
(餓漢式:在載入的時候建立物件{有可能整個專案執行下來沒有用這個物件,
而使用者沒有用但是卻建立了}){無執行緒安全問題,應為只有返回}
保證類在記憶體中只有一個物件。
(2)如何保證呢?
在本類中
A:構造私有(不讓在外接建立(new))
B:本身提供一個物件(為了保證只有一個物件)
C:對外提供公共的訪問方式(加static)
//保證內在
private Student(){};//構造私有(不讓外界創造物件)
//為了不讓外界訪問(直接賦值)加 private
private static Student s = new Student();
public static Student GetStudent(){//C:對外提供公共的訪問方式(為了外界直接訪問加static)
return s;
}*///2 單例模式 (懶漢式:在使用的時候建立){有執行緒安全問題:因為需要(共享資料s和多步驟)判斷,造物件,返回}
//懶漢式用了一種思想 :延時載入(用的時候再去建立)
//這種方法安全了 但影響效率
/* private Student(){};
private static Student s = null;
public synchronized static Student GetStudent(){//不安全 加鎖但浪費效能
1,s= new Student();//存在問題每次呼叫都要 建立物件{所以加個判斷 if(snull)}*
//s1,s2,s3
if(snull){
//s1,s2,s3
s=new Student();
}return s;
}*/
//懶漢式(安全高效模式)
private Student(){};
private static Student s = null;
public static Student GetStudent(){//不安全 加鎖
/1,s= new Student();//存在問題每次呼叫都要 建立物件{所以加個判斷 if(s==null)}
*/
if(snull){
// A, B
//只有第一次進來時有鎖子
synchronized (Student.class) {
//當ab 都進進來時
if(snull){
s=new Student();
}
}
}
return s;
}
}