1. 程式人生 > >如何編寫單例模型?(餓漢和飽漢模式)

如何編寫單例模型?(餓漢和飽漢模式)

package cn.kgc.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

//讀取配置檔案的工具類-單例模式
public class ConfigManager {
	private static ConfigManager configManager = new ConfigManager();
	private static Properties properties;
	//私有構造器-讀取資料庫配置檔案
	private ConfigManager(){
		String configFile = "database.properties";
		properties = new Properties();
		InputStream is = 
				ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
		try {
			properties.load(is);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/*//全域性訪問點-(懶漢模式)
	public static synchronized ConfigManager getInstance(){
		if(configManager == null){
			configManager = new ConfigManager();
		}
		return configManager;
	}*/
	
	//餓漢模式
	public static ConfigManager getInstance(){
		return configManager;
	}
	
	public String getValue(String key){
		return properties.getProperty(key);
	}
}