連線池Connection Pool 單例設計
阿新 • • 發佈:2019-01-06
連線池單例模式
1.私有化ComboPooledDataSource將其作為屬性,使其實現單例
2.DataSourceFactory實現懶漢模式,這樣作為屬性的連線池cpds也就變為了單例
3.從連線池中獲取連線Connection
程式碼如下:
package com.tcb.dao.uitls;
import java.sql.Connection;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/*
* 連線池單例模式
*
* 1.私有化ComboPooledDataSource將其作為屬性,使其實現單例
* 2.DataSourceFactory實現懶漢模式,這樣作為屬性的連線池cpds也就變為了單例
* 3.從連線池中獲取連線Connection
*/
public class DataSourceFactory {
//1.私有化ComboPooledDataSource將其作為屬性,使其實現單例
private ComboPooledDataSource cpds;
//2.DataSourceFactory實現懶漢模式
//2.1私有化構造方法--並初始化cpds
private DataSourceFactory() {
cpds = new ComboPooledDataSource("c3p0-config");
}
//2.2 私有化屬性
private static DataSourceFactory sFactory = null;
//2.3 返回SessionFactory單例
public static DataSourceFactory getSessionFactoryInstance() {
if (sFactory == null) {
sFactory = new DataSourceFactory();
}
return sFactory;
}
//3.從連線池中獲取連線Connection
public Connection getSession () throws Exception {
System.out.println("cpsd========="+cpds);
Connection connection = cpds.getConnection();
System.out.println("connection========="+connection);
return connection;
}
public static void main(String[] args) {
//測試
DataSourceFactory dataSourceFactory=DataSourceFactory.getSessionFactoryInstance();
DataSourceFactory dataSourceFactory2=DataSourceFactory.getSessionFactoryInstance();
try {
dataSourceFactory.getSession();
dataSourceFactory.getSession();
dataSourceFactory.getSession();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
測試結果: