讀取Properties文件(單例模式)

列子:如何用單例模式讀取配置文件信息,用以避免過多創建對象,浪費資源

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; } }


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