单例模式 之 属性管理器

来源:互联网 发布: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