1 桥接模式源码解析
1.1 源码解析1 jdk中的应用(驱动类)
1 桥接模式源码解析
1.1 源码解析1 jdk中的应用(驱动类)
步骤:
class.forName 调取驱动接口的静态块,触发驱动管理类DriverManager 的注册驱动方法,从而将该驱动放到CopyOnWriteArrayList中。
getConnect方法是通过传入url用户名密码。
针对不同的数据库,通过driverManager中的不同方法,获取的都是相同的接口,jdbc在最初的时候设计了一套接口,再由各个数据库公司实现这套接口。
重点:
实现(各种Driver如SqlDriver,OracleDriver等)和抽象(DriverManager的分离)分离
驱动接口:
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.mysql.jdbc; import java.sql.DriverManager; import java.sql.SQLException; public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException { } //class.forName 直接调用该静态块 static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can‘t register driver!"); } } }
驱动实现类:
public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException { } }
DriverManager:
public class DriverManager { // List of registered JDBC drivers private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<DriverInfo>(); private static volatile int loginTimeout = 0; private static volatile java.io.PrintWriter logWriter = null; private static volatile java.io.PrintStream logStream = null; // Used in println() to synchronize logWriter private final static Object logSync = new Object(); /* Prevent the DriverManager class from being instantiated. */ private DriverManager(){} /** *内部类,对driver进行封装 */ class DriverInfo { final Driver driver; DriverInfo(Driver driver) { this.driver = driver; } public boolean equals(Object other) { return (other instanceof DriverInfo) && this.driver == ((DriverInfo) other).driver; } public int hashCode() { return driver.hashCode(); } public String toString() { return ("driver[className=" + driver + "]"); } } //注册驱动的方法
public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException { /* Register the driver if it has not already been added to our list */ if(driver != null) { registeredDrivers.addIfAbsent(new DriverInfo(driver)); } else { // This is for compatibility with the original DriverManager throw new NullPointerException(); } println("registerDriver: " + driver);}
//获取数据库连接
@CallerSensitivepublic static Connection getConnection(String url, String user, String password) throws SQLException { java.util.Properties info = new java.util.Properties(); if (user != null) { info.put("user", user); } if (password != null) { info.put("password", password); } return (getConnection(url, info, Reflection.getCallerClass()));}}
原文地址:https://www.cnblogs.com/1446358788-qq/p/11523294.html
时间: 2024-10-31 09:24:33