单例模式 之 属性管理器
来源:互联网 发布:linux关闭图形界面 编辑:程序博客网 时间:2024/06/05 01:14
import java.io.*;
import java.util.Properties;
public class TestProperties {
private String M_FILE = "rc.properties";
private long lastModifiedTime = 0;
private static TestProperties testProperties = null;
private Properties properties = new Properties();
private File file = null;
//读取配置文件
private TestProperties() {
file = new File(M_FILE);
lastModifiedTime = file.lastModified();
//最后文件的修改时间来判断
if (lastModifiedTime == 0) {
System.out.println("FILE IS NOT FOUNT");
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//使用懒汉式加载类
public synchronized static TestProperties getInstance() {
if (null == testProperties) {
testProperties = new TestProperties();
}
return testProperties;
}
/**
*
* @param name 用户指定的查找名称
* @return 根据名称查找的值
*/
final public Object getConfigItem(String name) {
long newTime = file.lastModified();
//属性文件不存在
if(newTime == 0){
System.out.println("File not fount");
} else if (newTime > lastModifiedTime) { //文件已经修改,重新加载配置文件
properties.clear();
try {
properties.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
lastModifiedTime = newTime;
Object val = properties.getProperty(name);
if (val == null) {
System.out.println("can not fount this value according this name :" + name);
}
return val;
}
}
说明:
单例模式的三个要点:a.某个类只能有一个实例 b.必须自行创建这个事例 c.必须自行向整个系统提供这个实例
1. rc.properties 配置文件 格式为:key=value
2. 调用事例代码 Sysout.out.println(TestProperties.getInstance().getConfigItem("key") );
输出结果为: value
- 单例模式 之 属性管理器
- 文件管理器与设计模式-单例模式
- 静态属性 单例模式
- 单例模式的指针管理工具:参数管理器-资源管理核心
- 模式之单例模式
- 设计模式之单例
- Java之单例模式
- JavaScript之单例模式
- 设计模式之单例
- 单例模式之旅
- ios之单例模式
- 设计模式之 单例
- WPF之单例模式
- 设计模式之单例
- Java之单例模式
- JavaSE之单例模式
- IOS之单例模式
- Java之单例模式
- NHibernate学习之一:CompositeKey的实现
- 用代码说明Struts 1.0中的action
- 存储过程定义以及如何用SQL写一些存储过程实例
- 为什么要写博
- SourceInsight常用技巧
- 单例模式 之 属性管理器
- 如何读出Web.Config文件中的东东
- 股票投资01
- SourceInsight常用宏
- 流行音乐界有一个人叫Michael Jackson!
- 如何从菜鸟到游戏开发高手?
- C语言发展简史
- 主人、猫、老鼠编程面试题
- struts+spring+hibernate介绍