目录
工厂模式的工厂
DataSourceFactory是工厂角色的接口层
public interface DataSourceFactory {
  void setProperties(Properties props);
  DataSource getDataSource();
}
这个两个方法一个是设置DataSource的相关属性,一个是获取当前的dataSource
UnpooledDataSourceFactory实现了这个接口,它的构造方法中指定dataSource是UnpooledDataSource对象
public UnpooledDataSourceFactory() {
        this.dataSource = new UnpooledDataSource();
}
PooledDataSourceFactory继承了UnpooledDataSourceFactory,构造方法中返回了PooledDataSource对象,其他都是使用UnpooledDataSourceFactory的方法
public class PooledDataSourceFactory extends UnpooledDataSourceFactory {
    public PooledDataSourceFactory() {
        this.dataSource = new PooledDataSource();
    }
}
工厂模式的产品
DataSource的工厂模式的产品的接口,UnpooledDataSource和PooledDataSource都实现了这个方法,UnpooledDataSource是不使用数据库连接池,而PooledDataSource是使用数据库连接池
UnpooledDataSource的doGetConnection()方法:
    private Connection doGetConnection(String username, String password) throws SQLException {
        Properties props = new Properties();
        if (driverProperties != null) {
            props.putAll(driverProperties);
        }
        if (username != null) {
            props.setProperty("user", username);
        }
        if (password != null) {
            props.setProperty("password", password);
        }
        return doGetConnection(props);
    }
    private Connection doGetConnection(Properties properties) throws SQLException {
        initializeDriver();
        Connection connection = DriverManager.getConnection(url, properties);
        configureConnection(connection);
        return connection;
    }
这个方法就是典型的连接数据库的操作了:
- 调用initializeDriver()方法初始化数据库驱动,这个方法中进行jdbc驱动的初始化,注册到DriverManager中,同时保存到registeredDrivers中,registeredDrivers是UnpooledDataSource是成员变量,使用ConcurrentHashMap来进行存储,保证线程的安全性
 - Connection connection = DriverManager.getConnection(url, properties);
 - 创建数据库连接
 - 调用configureConnection()方法配置数据库的连接
 
PooledDataSource是使用数据库连接池来进行缓存数据库连接,但我们要设置合适的数据库连接池的最大连接数和最大空闲连接数
有了数据库连接池,在初始化的时候初始化数据库连接信息,缓存到连接池中,当需要连接数据库的时候从数据库连接池中获取,使用完后不需要关闭连接而是返还给连接池,方便下次使用。
总结
本文主要介绍了Mybatis的数据源模块,从工厂模式的角度分析了担任工厂模式的工厂角色的接口DataSourceFactory和它对应的实现类UnpooledDataSourceFactory、PooledDataSourceFactory,同时介绍了工厂模式的产品角色的DataSource接口和它对应的实现类UnpooledDataSource、PooledDataSource,UnpooledDataSource不使用数据库连接池,PooledDataSource使用了数据库连接池。

