單例模式 之 屬性管理器

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章