标签:单例模式
<span style="font-size:12px;">public class Emperor { private final static Emperor emperor =new Emperor(); private Emperor(){} public static Emperor instance(){ return emperor; } public void order(){ System.out.println("吾皇有旨"); } }</span>
<span style="font-size:12px;">public class Emperor { private final static Emperor emperor = null; private Emperor() { } public static synchronized Emperor instance() { if (emperor == null) { return new EmperorII(); } else { return emperor; } } public void order() { System.out.println("吾皇有旨"); } }</span>
<span style="font-size:12px;">import java.io.IOException; import java.io.InputStream; import java.util.Properties; //单例模式:可以保证系统中一个类只有一个实例,并且,这个实例容易被外界调用。好处就是节省系统的资源 //如果希望系统中的某个类的对象只有一个,这个时候你可以选择用单例 public class Myproperties extends Properties { private static Myproperties mypro=null; //对外提供的实例 /** * 单例的核心就是 构造方法私有化 */ private Myproperties(){ //比db.properties中读取所有的配置, //通过类的反射实例,获取classpath类路径下的资源文件db.properties,并建立一个流 InputStream is=this.getClass().getResourceAsStream("/db.properties"); try { this.load(is); //把流变为一个properties 结构的文档 ,从输入流 } catch (IOException e) { e.printStackTrace(); LogUtil.log.error(e.toString()); }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); LogUtil.log.error(e.toString()); } //关闭流 } } /** * 对外提供一个获取唯一实例的方法 * @return */ public static Myproperties getMyproperties(){ if( mypro==null){ mypro=new Myproperties(); } return mypro; } }</span>
<span style="font-size:12px;">/** * 获取数据库连接的方法 * @return:返回获取到的连接 */ public Connection getConnection() { try { con = DriverManager.getConnection(Myproperties.getMyproperties() .getProperty("url"), Myproperties.getMyproperties()); } catch (SQLException e) { e.printStackTrace(); LogUtil.log.error(e.toString()); } return con; }</span>
最近打了俩天的LOL,之前学的有点烦,没有实际应用。还好最近调整好了状态,keep going!
我是菜鸟,我在路上。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:单例模式
原文地址:http://blog.csdn.net/cjvs9k/article/details/46940007