1. 程式人生 > 實用技巧 >以輪播效果為案例談如何寫優質程式碼

以輪播效果為案例談如何寫優質程式碼

準備

在閱讀原始碼前,需要先clone原始碼 地址:https://github.com/mybatis/mybatis-3

Mybatis框架使用大量常見的設計模式,學習Mybatis原始碼我們主要學習以下幾點:

  • 學習大佬們的編碼思想及規範
  • 學習一些傳承下來的設計模式
  • 實踐java基礎理論

帶著問題閱讀原始碼

  • 問題1:原始碼中用了哪些設計模式?為什麼要用這些設計模式?
  • 問題2.Mybatis開啟除錯模式之後,能列印sql語句等資訊,這是怎麼實現的?實現過程中使用了什麼設計模式?假如有多個日誌實現,載入順序是什麼?

帶著這些個問題 我們去原始碼中找尋答案
首先我們先來看看原始碼包功能模組圖

Mybatis框架提供了一個頂層介面SqlSession

,核心處理層,基礎支撐層 這裡使用了一個常見的設計模式:外觀模式/門面模式
今天我們主要講解基礎支撐層日誌模組內部是如何處理的.

原始碼-logging

開啟原始碼專案,可以看到有20個目錄,這裡我們先不深入去看,把目光聚焦到logging目錄

開啟目錄,我們可以看到映入眼簾的就是 Log LogException LogFactory (紅色部分)和具體的日誌實現(黃色部分),

開啟Log介面,我們可以看到Log介面提供了七個介面方法

實現這個介面的實現方法我們看看都是誰呢,可以看到就是我們剛剛黃色框框部分,那麼他是怎麼來處理那麼多Log實現的呢,別急,繼續往下看

我們隨便開啟一個Log的實現類,可一看到實際上這並不是真正的實現了所需要的Log只是在對每個用到的Log實現做了引數適配而已
(其他的類也是類似,這裡使用了介面卡模式)

那麼有那麼多日誌實現,他的載入順序是什麼呢.到這裡我們會想到剛剛看到的LogFactory類,大叫都知道工廠方法就是用來獲取例項的既然要獲取例項那麼他的處理也肯定在工廠內部處理完畢了(這裡使用了簡單工廠模式) 那麼我們開啟LogFactory類來看看他的載入順序到底是怎麼實現的:

import java.lang.reflect.Constructor;


public final class LogFactory {


  public static final String MARKER = "MYBATIS";

  private static Constructor<? extends Log> logConstructor; //定義logConstructor 他繼承於Constructor

  static {	//載入順序在這裡.初始化時必定按照這個順序執行,可以發現下面這一排排就是我們剛剛看到的各個介面卡
    tryImplementation(LogFactory::useSlf4jLogging);
    tryImplementation(LogFactory::useCommonsLogging);
    tryImplementation(LogFactory::useLog4J2Logging);
    tryImplementation(LogFactory::useLog4JLogging);
    tryImplementation(LogFactory::useJdkLogging);
    tryImplementation(LogFactory::useNoLogging);
  }

  private LogFactory() {
    // 在這裡私有化構造器 就不能通過new來建立例項了
  }

  public static Log getLog(Class<?> clazz) {//第一步.如果我們需要一個Log 那麼我們就呼叫這個方法,傳入需要的類即可
    return getLog(clazz.getName());
  }

  public static Log getLog(String logger) {//第二步.根據類的名字獲取Log實現.如果獲取不到會報錯,這個logConstructor就是我們上面的,他內部在初始化時已經通過static的靜態程式碼塊進行了處理,所以會處理為對應的日誌實現,
    try {
      return logConstructor.newInstance(logger);
    } catch (Throwable t) {
      throw new LogException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
    }
  }

  public static synchronized void useCustomLogging(Class<? extends Log> clazz) {
    setImplementation(clazz);
  }

  public static synchronized void useSlf4jLogging() {//每個靜態同步方法都是去呼叫setImplementation
    setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
  }

  public static synchronized void useCommonsLogging() {
    setImplementation(org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.class);
  }

  public static synchronized void useLog4JLogging() {
    setImplementation(org.apache.ibatis.logging.log4j.Log4jImpl.class);
  }

  public static synchronized void useLog4J2Logging() {
    setImplementation(org.apache.ibatis.logging.log4j2.Log4j2Impl.class);
  }

  public static synchronized void useJdkLogging() {
    setImplementation(org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl.class);
  }

  public static synchronized void useStdOutLogging() {
    setImplementation(org.apache.ibatis.logging.stdout.StdOutImpl.class);
  }

  public static synchronized void useNoLogging() {
    setImplementation(org.apache.ibatis.logging.nologging.NoLoggingImpl.class);
  }

  private static void tryImplementation(Runnable runnable) {//將傳入的程式碼塊執行,注意這裡是.run 不是.start 
    if (logConstructor == null) {//如果還沒有實現才執行
      try {
        runnable.run();
      } catch (Throwable t) {//如果載入這個實現出現了異常,如:ClassNotFoundException 這個時候直接忽略,等待下一個實現呼叫
        // ignore
      }
    }
  }
		//在獲取到一個實現成功後 會呼叫這個方法來初始化Log
  private static void setImplementation(Class<? extends Log> implClass) {
    try {
      Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
      Log log = candidate.newInstance(LogFactory.class.getName());
      if (log.isDebugEnabled()) {
        log.debug("Logging initialized using '" + implClass + "' adapter.");
      }
      logConstructor = candidate;
    } catch (Throwable t) {
      throw new LogException("Error setting Log implementation.  Cause: " + t, t);
    }
  }

}

回顧一下問題:原始碼中用了哪些設計模式?
到目前我們看到Mybatis使用了 1.外觀模式/門面模式 2.介面卡模式 3簡單工廠模式
到這裡我們已經拿到了Log的例項不管他是通過log4j還是slf4j的實現,那他是怎麼實現對日誌進行增強的呢 怎麼打印出來的SQL語句和引數以及結果計數的?
如果想要輸出這些資訊,那麼首先肯定要獲取到這些資訊.
下面我們就去看這塊,看看他是怎麼獲取和存貯這些資訊的.

public abstract class BaseJdbcLogger {

  protected static final Set<String> SET_METHODS;//set方法容器
  protected static final Set<String> EXECUTE_METHODS = new HashSet<>();//執行方法容器

  private final Map<Object, Object> columnMap = new HashMap<>();//列的鍵值對

  private final List<Object> columnNames = new ArrayList<>();//所有key的列表
  private final List<Object> columnValues = new ArrayList<>();//所有value的列表

  protected final Log statementLog;  // Log實現
  protected final int queryStack;

  /*
   * Default constructor
   */
  public BaseJdbcLogger(Log log, int queryStack) {//預設的構造
    this.statementLog = log;
    if (queryStack == 0) {
      this.queryStack = 1;
    } else {
      this.queryStack = queryStack;
    }
  }

  static {//初始化 就載入兩個容器 這兩個容器用來裝所有的預編譯set引數的方法和所有執行方法
    SET_METHODS = Arrays.stream(PreparedStatement.class.getDeclaredMethods())//這裡使用JAVA8新特性將PreparedStatement類的所有set開頭的方法對映成一個Set
            .filter(method -> method.getName().startsWith("set"))
            .filter(method -> method.getParameterCount() > 1)
            .map(Method::getName)
            .collect(Collectors.toSet());

    EXECUTE_METHODS.add("execute");//將4個執行方法新增到EXECUTE_METHODS這個Set
    EXECUTE_METHODS.add("executeUpdate");
    EXECUTE_METHODS.add("executeQuery");
    EXECUTE_METHODS.add("addBatch");
  }

  protected void setColumn(Object key, Object value) {
    columnMap.put(key, value);
    columnNames.add(key);
    columnValues.add(value);
  }

  protected Object getColumn(Object key) {
    return columnMap.get(key);
  }

  protected String getParameterValueString() {
    List<Object> typeList = new ArrayList<>(columnValues.size());
    for (Object value : columnValues) {
      if (value == null) {
        typeList.add("null");
      } else {
        typeList.add(objectValueString(value) + "(" + value.getClass().getSimpleName() + ")");
      }
    }
    final String parameters = typeList.toString();
    return parameters.substring(1, parameters.length() - 1);
  }

  protected String objectValueString(Object value) {
    if (value instanceof Array) {
      try {
        return ArrayUtil.toString(((Array) value).getArray());
      } catch (SQLException e) {
        return value.toString();
      }
    }
    return value.toString();
  }

  protected String getColumnString() {
    return columnNames.toString();
  }

  protected void clearColumnInfo() {
    columnMap.clear();
    columnNames.clear();
    columnValues.clear();
  }

  protected String removeExtraWhitespace(String original) {
    return SqlSourceBuilder.removeExtraWhitespaces(original);
  }

  protected boolean isDebugEnabled() {
    return statementLog.isDebugEnabled();
  }

  protected boolean isTraceEnabled() {
    return statementLog.isTraceEnabled();
  }

  protected void debug(String text, boolean input) {
    if (statementLog.isDebugEnabled()) {
      statementLog.debug(prefix(input) + text);
    }
  }

  protected void trace(String text, boolean input) {
    if (statementLog.isTraceEnabled()) {
      statementLog.trace(prefix(input) + text);
    }
  }

  private String prefix(boolean isInput) {
    char[] buffer = new char[queryStack * 2 + 2];
    Arrays.fill(buffer, '=');
    buffer[queryStack * 2 + 1] = ' ';
    if (isInput) {
      buffer[queryStack * 2] = '>';
    } else {
      buffer[0] = '<';
    }
    return new String(buffer);
  }

}

到這我們知道了他是怎麼存貯資訊的獲取的方式就是在呼叫時通過存貯的方法和set方法列表來查詢,那麼他是什麼時候被呼叫呢?仔細看看這個圖我們發現了端倪 在BaseJdbcLogger下面還有

  • ConnectionLogger
  • PreparedStatementLogger
  • ResultSetLogger
  • StatementLogger
    這些不就是我們很眼熟的流程嗎 獲取資料庫連線--> 預編譯SQL--> 執行SQL--> 獲取結果

    我們隨便開啟一個 看看他們是怎麼在自己的一畝三分地幹活的
public final class ConnectionLogger extends BaseJdbcLogger implements InvocationHandler {//繼承於BaseJdbcLogger 實現InvocationHandler 看到InvocationHandler 就會想到->代理模式

  private final Connection connection;//他實要代理的就是這connection

  private ConnectionLogger(Connection conn, Log statementLog, int queryStack) {
    super(statementLog, queryStack);
    this.connection = conn;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] params)
      throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, params);
      }
      if ("prepareStatement".equals(method.getName()) || "prepareCall".equals(method.getName())) {//判斷方法名是不是這兩中的一個 短語或 有一個就為true
        if (isDebugEnabled()) {//原來開啟debug 就會打出日誌是在這裡呀
          debug(" Preparing: " + removeExtraWhitespace((String) params[0]), true);
        }
        PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);// 通過connection建立了PreparedStatement
        stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack); //把stmt 傳過去給PreparedStatementLogger的newInstance 建立了一個stmt的代理返回
        return stmt;//注意這裡返回的不是真實stmt 而是代理過後的stmt
      } else if ("createStatement".equals(method.getName())) {//如果是建立Statement
        Statement stmt = (Statement) method.invoke(connection, params); //拿到連線去建立一個Statement
        stmt = StatementLogger.newInstance(stmt, statementLog, queryStack);//把Statement傳進StatementLogger 獲取Statement的代理物件來返回
        return stmt;//注意這裡返回的不是真實stmt 而是代理過後的stmt
      } else {
        return method.invoke(connection, params);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

  /**
   * Creates a logging version of a connection.
   *
   * @param conn
   *          the original connection
   * @param statementLog
   *          the statement log
   * @param queryStack
   *          the query stack
   * @return the connection with logging
   */
  public static Connection newInstance(Connection conn, Log statementLog, int queryStack) {
    InvocationHandler handler = new ConnectionLogger(conn, statementLog, queryStack);
    ClassLoader cl = Connection.class.getClassLoader();
    return (Connection) Proxy.newProxyInstance(cl, new Class[]{Connection.class}, handler);
  }

  /**
   * return the wrapped connection.
   *
   * @return the connection
   */
  public Connection getConnection() {
    return connection;
  }
public final class PreparedStatementLogger extends BaseJdbcLogger implements InvocationHandler {

  private final PreparedStatement statement; //還是一樣 這裡是被代理的實際物件

  private PreparedStatementLogger(PreparedStatement stmt, Log statementLog, int queryStack) {
    super(statementLog, queryStack);
    this.statement = stmt;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {//增強的邏輯在這裡
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, params);
      }
      if (EXECUTE_METHODS.contains(method.getName())) {//還記得那幾個容器嗎 用來儲存各種方法的  現在他來了
        //開啟DEBUG 我就把引數打印出來
        if (isDebugEnabled()) {
          debug("Parameters: " + getParameterValueString(), true);
        }
        clearColumnInfo();
        if ("executeQuery".equals(method.getName())) {
          ResultSet rs = (ResultSet) method.invoke(statement, params);//獲取到一個resultset
          return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);//把resultset 也代理了來返回
        } else {
          return method.invoke(statement, params);
        }
      } else if (SET_METHODS.contains(method.getName())) {
        if ("setNull".equals(method.getName())) {
          setColumn(params[0], null);
        } else {
          setColumn(params[0], params[1]);
        }
        return method.invoke(statement, params);
      } else if ("getResultSet".equals(method.getName())) {
        ResultSet rs = (ResultSet) method.invoke(statement, params);
        return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);
      } else if ("getUpdateCount".equals(method.getName())) {
        int updateCount = (Integer) method.invoke(statement, params);
        if (updateCount != -1) {
          debug("   Updates: " + updateCount, false);
        }
        return updateCount;
      } else {
        return method.invoke(statement, params);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

  /**
   * Creates a logging version of a PreparedStatement.
   *
   * @param stmt - the statement
   * @param statementLog - the statement log
   * @param queryStack - the query stack
   * @return - the proxy
   */
  public static PreparedStatement newInstance(PreparedStatement stmt, Log statementLog, int queryStack) {
    InvocationHandler handler = new PreparedStatementLogger(stmt, statementLog, queryStack);
    ClassLoader cl = PreparedStatement.class.getClassLoader();
    return (PreparedStatement) Proxy.newProxyInstance(cl, new Class[]{PreparedStatement.class, CallableStatement.class}, handler);
  }

  /**
   * Return the wrapped prepared statement.
   *
   * @return the PreparedStatement
   */
  public PreparedStatement getPreparedStatement() {
    return statement;
  }

}

最後是ResultSetLogger

  @Override
  public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {//ResultSetLogger的增強方法
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, params);
      }
      Object o = method.invoke(rs, params);
      if ("next".equals(method.getName())) { 
        if ((Boolean) o) {
          rows++;//只要還有下一條next,就記數加1  rows++;
          if (isTraceEnabled()) {
            ResultSetMetaData rsmd = rs.getMetaData();
            final int columnCount = rsmd.getColumnCount();
            if (first) {
              first = false;
              printColumnHeaders(rsmd, columnCount);
            }
            printColumnValues(columnCount);
          }
        } else {
          debug("     Total: " + rows, false);//開啟debug情況下 打印出總數計數
        }
      }
      clearColumnInfo();
      return o;
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

到這裡我們基本已經摸完了這塊邏輯 現在覆盤一下問題

  • 問題1.原始碼中用了哪些設計模式?為什麼要用這些設計模式?
    門面/外觀模式 介面卡模式 代理模式 簡單工廠模式. 為什麼要使用這些模式 太長了我就不寫了,大家自行總結
  • 問題2.Mybatis開啟除錯模式之後,能列印sql語句等資訊,這是怎麼實現的?實現過程中使用了什麼設計模式?假如有多個日誌實現,載入順序是什麼?
    在除錯模式能列印日誌,是mybatis框架在實際執行時對物件進行了代理,進行了增強.他使用了代理設計模式.他實現日誌的順序是:
  static {
    tryImplementation(LogFactory::useSlf4jLogging);
    tryImplementation(LogFactory::useCommonsLogging);
    tryImplementation(LogFactory::useLog4J2Logging);
    tryImplementation(LogFactory::useLog4JLogging);
    tryImplementation(LogFactory::useJdkLogging);
    tryImplementation(LogFactory::useNoLogging);
  }

加群讓我們一起學習吧

關注公眾號:java寶典