单例模式
顾名思意 就是在虚拟机中只有一个实例。通过 实例的方法来调用,实现逻辑。所以,就不需要静态的公共方法。
单例模式,要主意,实例化时候,线程同步的问题。
package four.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class utilsSingle {
// 和上个非单例的相比 成员变量不是静态的
private String url = "jdbc:mysql://localhost:3306/jdbc";
private String user = "root";
private String password = "root";
// 单例成员变量 是 静态的
private static utilsSingle instance = null;
private utilsSingle() {
}
public static utilsSingle getUtilsSingleInstance() {
// 双重枷锁
if(instance == null){
// 同步化语句块,不是同步化方法,这样
// 只有初始化单例时第一次加锁
synchronized (utilsSingle.class) {
if(instance == null){
instance = new utilsSingle();
}
}
}
return instance;
}
static {
// 保证注册一次-> 1静态代码块类被加载到虚拟机时被执行
try {
// 1 注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
// 单例模式不使用静态方法
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 单例模式不使用静态方法
public void free(Connection connection,
Statement statement,
ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}