列子:如何用单例模式读取配置文件信息,用以避免过多创建对象,浪费资源
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; } }