使用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;附上测试工程源码)