使用enum關鍵字來實現單例模式的好處是可以提供序列化機制,絕對防止多次實例化,即使是在面對複雜的序列化或者反射攻擊的時候。—— 來自《Effective Java》
【1】配置文件test.properties
#info
a_text=I am text A
b_text=I am text B
【2】枚舉實例AppContext.java
package hhf.propertie;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 讀取配置文件
* @author HHF
* 2014年12月29日
*/
public enum AppContext {
INSTANCE;
private volatile Properties configuration = new Properties();
public void init() {
InputStream is = this.getClass().getResourceAsStream("/test.properties");
if (is != null) {
try {
this.configuration.clear();
this.configuration.load(is);
} catch (IOException e) {
} finally {
try {
is.close();
} catch (Throwable t) {}
}
}
}
public String getConfigValue(String key) {
return this.configuration.getProperty(key);
}
}
【3】讀取配置文件臨時保存數據到常量內SystemConstants.java
package hhf.propertie;
/**
* 緩存配置文件信息
* @author HHF
* 2014年12月29日
*/
public class SystemConstants {
//info
public static final String DATA_A = AppContext.INSTANCE.getConfigValue("a_text");
public static final String DATA_B = AppContext.INSTANCE.getConfigValue("b_text");
}
【4】測試文件Main.java
public class Main {
public static void main(String[] args) {
AppContext.INSTANCE.init();
System.out.println(SystemConstants.DATA_A);
System.out.println(SystemConstants.DATA_B);
}
}
一個enum常量(這裏是INSTANCE)代表了一個enum的實例,enum類型只能有這些常量實例。標準保證enum常量(INSTANCE)不能被克隆,也不會因爲反序列化產生不同的實例,想通過反射機制得到一個enum類型的實例也是不行的。
(PS;附上測試工程源碼)