簡介
單例模式,是一種常用的軟件設計模式。在它的核心結構中只包含一個被稱爲單例的特殊類。通過單例模式可以保證系統中一個類只有一個實例。即一個類只有一個對象實例。—《百度百科》
實現方法
- 構造方法私有化;
- 提供一個公共的靜態方法,此方法獲取一個當前類對象;
- 類中定義一個私有的靜態當前類引用。
代碼實現
- 懶漢式(常用):在真正用到的時候纔會去創建對象
public class User {
/**
* 懶漢式
*/
private static User user=null;
private User() {}
private static User getUserInstance(){
if(user==null){
user=new User();
}
return user;
}
}
但是懶漢式存在線程安全問題,可以使用同步鎖機制,只需在獲取實例的方法上加上Synchronized即可。
當使用同步鎖機制後,又會存在另一個問題,就是在多線程併發訪問的情況下,每個線程每次獲取實例都要判斷下鎖,效率比較低,爲了提高效率,我們可以使用雙重判斷的方法。
public class User02 {
/**
* 懶漢式,解決使用雙重判斷解決,多線程併發訪問效率低的問題
* 類鎖:在代碼中的方法上加了static和synchronized的鎖,
* 或者synchronized(xxx.class)的代碼段
*/
private static User02 user=null;
private User02() {}
private static User02 getUserInstance(){
//如果第一個線程獲取了單例的實例對象
//後面線程再獲取實例的時候不需要進入同步代碼塊中了
if(user==null){
//同步代碼塊用的鎖是單例的字節碼文件對象,且只能用這個鎖
synchronized (User02.class) {
if(user==null){
user=new User02();
}
}
}
return user;
}
}
- 餓漢式:一開始就會建立單例對象
public class Student {
/**
* 惡漢式
*/
private static Student student=null;
private Student() {}
static{
student=new Student();
}
private static Student getStudentInstance(){
return student;
}
}
注意:Servlet並不是單例,只是容器只實例化它一次,表現出單例的效果而已