设计模式--单例模式

//懒汉式---线程不安全---解决办法是添加同步代码块
//添加同步锁后会降低运行效率----解决办法是在同步代码块外增加判断
class Single{
  private static Single s=null;
  private Single(){}
  private static Single getInstance(){
    if(s==null){//提高代码的运行效率
      synchronized(Single.class){//解决单例模式的安全问题
          if(s==null){
            s=new Single();
            }
      }
    }
    return s;
  }
 
}


//饿汉式
class Single{
  private static final Single s=new Single();
  private Single(){}
  public static Single getInstance(){
    return s;
}
}


-----------------------------------------------
package
com.wuyong.util; import java.io.InputStream; import java.util.Properties; /** * * @author wuyong * @email 382999338@qq.com * @date2016年9月1日下午6:59:33 * * *读取配置文件的工具类---单列模式---懒汉模式--延迟加载 * * 步骤: * * 1.创建私有的构造器,进行配置文件的读取 * 2.创建全局访问点,通过单列模式设置实列化的个数,返回configManager实列 * 3.通过key获得对应的value */ public class ConfigManager { private static ConfigManager configManager; private static Properties properties;//Properties用来操作properties文件 //私有的构造器,进行配置文件的读取 private ConfigManager(){ String configFile="jdbc.properties"; properties=new Properties(); try { //通过classpath找资源 //在当前类所在包的根目录下找到相应的configFile文件 //getClassLoader()返回类加载器 //getResourceAsStream(configFile)返回InputStream对象 InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile); properties.load(is);//读取配置文件 is.close(); } catch (Exception e) { // TODO: handle exception } } /* *线程不安全,在并发环境下,很有可能会出现多个configManager实列 *需要考虑同步 , 可以加同步锁 synchronized * 懒汉模式 (线程不安全--解决办法1.方法体加同步锁synchronized 2.双重校验锁) * 在类加载的时候不创建实列,运行的时候创建。 * 优点:类加载快 * 缺点:效率低,在运行时获取对象速度慢 * * */ //全局访问点 //通过单列模式设置实列化的个数 public static synchronized ConfigManager getInstance(){ if (configManager==null) { configManager=new ConfigManager(); } return configManager; } //通过key获得对应的value public String getValue(String key){ return properties.getProperty(key); } /*//双重校验锁 private static ConfigManager cManager; //私有的构造器 private ConfigManager(){ String configFile="database.properties"; properties=new Properties(); try { //通过classpath找资源 //在当前类所在包的根目录下找到相应的configFile文件 InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile); properties.load(is); is.close(); } catch (Exception e) { // TODO: handle exception } }
//双重校验锁 public static ConfigManager getInstance(){ if (cManager==null) { synchronized(ConfigManager.class){ if (cManager==null) { cManager=new ConfigManager(); } } } return cManager; }
*/ }
package com.wuyong.util;

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

/**
 * 
 * @author wuyong
 * @email 382999338@qq.com
 * @date2016年9月1日下午7:02:16
 * 单列模式---饿汉模式:(线程安全)
在类加载的时候,就完成初始化。所以累加载慢,但在运行时获取对象快
 */

public class ConfigManager2 {
    
    //类加载的时候,自动进行初始化
    private static ConfigManager2 configManager2=new ConfigManager2();
    private static Properties properties;
    
    //私有的构造器
    private ConfigManager2(){
        String configFile="database.properties";
        properties=new Properties();
        
    try {
        //通过classpath找资源
        //在当前类所在包的根目录下找到相应的configFile文件
        InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
        properties.load(is);
        is.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    
    }
    
    
    /*
         * 
     * 饿汉模式:(线程安全)
     * 在类加载的时候,就完成初始化。所以l类加载慢,但在运行时获取对象快
     */
    //全局访问点
    public static ConfigManager2 getInstance(){
        return configManager2;
    }
    
    public String getValue(String key){
        return properties.getProperty(key);
    }
        
}

上面的两个工具类用在JDBC连接数据库时,工具类创建configManager实列,通过configManager实列获取数据库连接。

在BaseDao中

package com.wuyong.dao;

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.wuyong.util.ConfigManager;

/**
 * 
 * @author wuyong
 * @email 382999338@qq.com
 * @date2016年9月1日下午7:23:14
 */


/*
 * 操作数据库的基类---静态类
 * 
 * 方法:
 * 1.获取数据库连接:public static Connection getConnection()
 *             步骤:
 *                     获取porperties文件,的value值
 *                     加载类的驱动
 *                     获取连接
 *                     返回连接
 * 
 * 2.查询操作:public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params) 
            throws SQLException
                    步骤:
                        执行SQL
                        接收结果集
                        返回结果集
    3.更新操作:    public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params)
            throws Exception
                    步骤:
                        执行SQL
                        接收影响的行数
                        返回影响的行数
    4.关闭资源:public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet)
 *             步骤:
 *                     关闭资源
 *                     GC回收
 *                     返回falg
 */
public class BaseDao {

    //获取数据库连接
    public static Connection getConnection(){
        String driver=ConfigManager.getInstance().getValue("driver");
        String url=ConfigManager.getInstance().getValue("url");
        String username=ConfigManager.getInstance().getValue("username");
        String password=ConfigManager.getInstance().getValue("password");

        Connection connection=null;

        //类加载

        try {
            Class.forName(driver);
            connection=DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;

    }


    //关闭资源
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag=true;
        if (resultSet!=null) {
            try {
                resultSet.close();
                resultSet=null;//GC回收
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                flag=false;
            }
        }

        if (preparedStatement!=null) {
            if (preparedStatement!=null) {
                try {
                    preparedStatement.close();
                    preparedStatement=null;//GC回收
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    flag=false;
                }
            }

            if (connection!=null) {
                try {
                    connection.close();
                    connection=null;//GC回收
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    flag=false;
                }
            }


        }
        return flag;
    }
    
    
    //查询操作
    public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params) 
            throws SQLException{//dao层的异常要抛出,在service层接收
        
        preparedStatement=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1, params[i]);
        }
        resultSet=preparedStatement.executeQuery();
        return resultSet;
    }
    
    //更新操作
    public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params)
            throws Exception{
        
        int updateRows=0;
        preparedStatement=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1, params[i]);
        }
        updateRows=preparedStatement.executeUpdate();
        return updateRows;
    }
}
原文地址:https://www.cnblogs.com/fifiyong/p/5831033.html