1. 程式人生 > >單例模式、懶漢模式以及餓漢模式的區別及應用

單例模式、懶漢模式以及餓漢模式的區別及應用

1.單例模式
單例模式就是系統執行期間,有且僅有一個例項。它有三個必須滿足的關鍵點:
(1)一個類只有一個例項。這是滿足單例模式最基本的要求,若滿足這個關鍵點,只能提供私有的構造器,即保證不能隨意建立該類的例項。示例如下:
//讀取配置檔案的工具類—單例模式
public class Config{
private static Properties properties;
//私有構造器–讀取資料庫配置檔案
private Config(){
String configFile=“dataBase.properties”;
properties =new Properties();
InputStream is=Config.class.getClassLoader().getResourceAsStream(configFile);
try{
properties.load(is);
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
在上述程式碼中,將讀取配置檔案的I/O操作放入私有構造器,這樣可以有效保證I/O操作在整個系統執行期間僅被執行一次,以解決資源消耗問題。
(2)它必須自行建立這個例項。對於這一點,正是體現了:單例模式的有且僅有一個例項這一特性,我們在保證唯一性時,也必須保證提供一個例項,但是需要它自行建立,於是我們在之前的程式碼中新增一個Config型別的靜態私有物件,以便向外界提供該類例項時使用。
示例如下:
//讀取配置檔案的工具類—單例模式
public class Config{
[color=#FF0000]private static Config config;[/color]
private static Properties properties;
//私有構造器–讀取資料庫配置檔案
private Config(){
String configFile=“dataBase.properties”;
properties =new Properties();
InputStream is=Config.class.getClassLoader().getResourceAsStream(configFile);
try{
properties.load(is);
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
(3) 它必須自行向整個系統提供這個例項。
為了能夠被其他類獲取這個例項,同時又不能自行建立該類的例項,於是我們還有新增一個公有的靜態方法,該方法建立或者獲取它本身的私有物件並返回。關鍵程式碼如下:
//讀取配置檔案的工具類—單例模式
public class Config{
[color=#FF0000]private static Config config;[/color]
private static Properties properties;
//私有構造器–讀取資料庫配置檔案
private Config(){
String configFile=“dataBase.properties”;
properties =new Properties();
InputStream is=Config.class.getClassLoader().getResourceAsStream(configFile);
try{
properties.load(is);
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
//全域性訪問點
public static Config getInstance(){
if(confignull){
config=new Config();
}
return config;
}
}
滿足以上三點才是一個完整的單例模式,不過在多執行緒併發的情況下使用單例模式時,它存在嚴重的弊端,如果執行緒不安全,很有可能會出現多個config例項,於是我們可以使用懶漢模式來解決多執行緒併發的問題。
2.懶漢模式即在類載入時不建立例項,採用延遲載入的方式,在執行呼叫時建立例項,即在上述程式碼中的全域性訪問的方法中做如下修改:
//全域性訪問點
public static synchronized Config getInstance(){
if(config

null){
config=new Config();
}
return config;
}
不過在使用此模式時,雖然解決了執行緒安全的問題,但是工作效率大大降低,所以我們使用餓漢模式來完善以上缺陷。
3.餓漢模式
餓漢模式即在類載入的時候完成了初始化操作,所以在類載入時較慢,但是獲取物件的速度很快。並且由於餓漢模式在類初始化的時候就已經自行例項化了,所以不存線上程安全的問題,但是由於每載入類就要例項化一次物件,導致資源的佔用很高,所以我們可以說懶漢模式是用時間換空間而餓漢模式則是用空間換時間。
餓漢模式的示例如下:
public class Config{
[color=#FF0000]private static Config config=new Config();[/color]
private static Properties properties;
//私有構造器–讀取資料庫配置檔案
private Config(){
String configFile=“dataBase.properties”;
properties =new Properties();
InputStream is=Config.class.getClassLoader().getResourceAsStream(configFile);
try{
properties.load(is);
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
//全域性訪問點
public static Config getInstance(){
return config;
}
}