列子:如何用單例模式讀取配置文件信息,用以避免過多創建對象,浪費資源
db.properties文件用來存放數據庫的相關信息
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=scott
password=tiger
單例類讀取信息:
public class SingleInstance extends Properties {
/**
*
*/
//私有靜態變量存放已有的實例
private static SingleInstance instance;
//將這個類隱藏,不允許外部類構造此類實例
private SingleInstance() throws DBLinkException{
//讀取配置信息
InputStream is=getClass().getResourceAsStream("../meta/db.properties");
try {
load(is);
} catch (Exception e) {
//拋出自定義異常
throw new DBLinkException("未能讀取到數據庫配置文件");
}
}
//建立一個外部類可以得到的單例
public static SingleInstance getInstance() throws DBLinkException{
if(instance==null){
instance=new SingleInstance();
return instance;
}
return instance;
}
}