单列模式-编写类ConfigManager读取属性文件

database.properties :--->
  jdbc.driver_class=com.mysql.jdbc.Driver
  jdbc.connection.url=jdbc:mysql://127.0.0.1:3306/news?useUnicode=true$characterEncoding=utf8-8
  jdbc.connection.username=root
  jdbc.connection.password=1234
 
========单例模式=========:运行期间有且仅有一个实例
 关键点:
  1. 一个类只有一个实例---最基本的--(只提供私有的构造器)
  2. 它必须自行创建这个实例--(定义了静态的该类的私有对象)
  3. 它必须自行向整个系统提供这个实例--(提供一个静态的公有的方法,返回创建或者获取本身的静态私有对象)
 -----------------------------------------------------------
  懒汉模式:(线程不安全,在并发环境下,很有可能会出现多个configManager实列------
-----------需要考虑同步 1、方法体加同步 synchronized 2、双重校验锁)
     在类加载的时候,不创建实例,运行调用的时候创建。
    优点:类加载快
    缺点:效率低,在运行时获取对象速度慢
 -----------------------------------------------------------
   饿汉模式:(线程安全)
          在类加载的时候,就完成初始化。
          所以类加载慢,但是在运行时获取对象快
    1.如这种写法
private static ConfigManager configManager2 = new ConfigManager();
    2. 或者这样写
private static ConfigManager configManager;
static(){
    configManager = new ConfigManager();
}

  3.如果有要求需要实现延迟加载,通过静态内部类;

     保证类加载的速度

--(外部调用 test()方法时,静态内部类实现了延时加载)

 

public class Singleton {
	//静态内部类 lazy loading
	private static Singleton singleton;
	
	private Singleton(){}
	
	private static class SingletonHelper{
		private static final Singleton INSTANCE = new Singleton();
	}
	
	public static Singleton getInstance(){
		return SingletonHelper.INSTANCE;
	}
	
	public static void test(){
		System.out.println("test===" + singleton.toString());
	}
	
}

 

 

----------------------------------------------------------------------

 

-----------------------------------------------------------------------
 

package cn.news.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

//读取配置文件的工具类--单例模式
public class ConfigManager {
	//读取配置文件properties.load(inputstream);
	private static ConfigManager configManager;
	private static Properties properties;
	private ConfigManager(){
		String configFile="database.properties";
		properties = new Properties();
		InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
		try {
			properties.load(is);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static ConfigManager getInstance(){
		if(configManager==null){
			configManager = new ConfigManager();
		}
		return configManager ;
	}
	
	//取得key对应的value;
	public String getString(String key){
		return properties.getProperty(key);
	}
}

 ================================================================================

 

=================================================================================

package com.news.util;
import java.io.InputStream;
import java.util.Properties;
/**
 * 
 * *读取配置文件的工具类---单列模式---懒汉模式--延迟加载
 * 
 * 步骤:
 *
 * 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);
    }
        
    
    /*//双重校验锁
     public static ConfigManager getInstance(){
            if (cManager==null) {
                synchronized(ConfigManager.class){
                    if (cManager==null) {
                        cManager=new ConfigManager();
                    }
                }
            }
            return cManager;
        }*/
}

 ===================================================================================================

===================================================================================================

package com.news.util;
import java.io.InputStream;
import java.util.Properties;
/**
 * 单列模式---饿汉模式:(线程安全)
在类加载的时候,就完成初始化。所以类加载慢,但在运行时获取对象快
 */
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) {
    }   
    }

    //全局访问点
    public static ConfigManager2 getInstance(){
        return configManager2;
    }
    
    public String getValue(String key){
        return properties.getProperty(key);
    }    
}

 --------------------------------------------------------------------------------------------------------------------------------------

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

import java.sql.Connection;

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

import com.util.ConfigManager;

/*
 * 操作数据库的基类---静态类
 * 
 * 方法:
 * 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;
    }
}

 

 

  • 大小: 96.3 KB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值