Mybatis源码单例模式详解

定义

单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

特点

1、一是某个类只能有一个实例;
2、二是它必须自行创建这个实例;
3、三是它必须自行向整个系统提供这个实例。
4、单例模式是一种对象创建型模式。
5、单例模式又名单件模式或单态模式。

源码实例

在Mybatis中有两个地方用到单例模式,ErrorContext和LogFactory,其中ErrorContext是用在每个线程范围内的单例,用于记录该线程的执行环境错误信息,而LogFactory则是提供给整个Mybatis使用的日志工厂,用于获得针对项目配置好的日志对象。

1. 获取ErrorContext实例

ErrorContext是用在每个线程范围内的单例,用于记录该线程的执行环境错误信息。

代码片段

public class ErrorContext {
  private static final ThreadLocal<ErrorContext> LOCAL = new ThreadLocal<>();

  private ErrorContext() {
  }

  public static ErrorContext instance() {
    //先获取本线程的该实例,如果没有就创建该线程独有的ErrorContext
    ErrorContext context = LOCAL.get();
    if (context == null) {
      context = new ErrorContext();
      LOCAL.set(context);
    }
    return context;
  }
}

2.获取org.slf4j.Logger 实例对象

LogFactory没有实现获取自身的方式,只是当成一个提供日志打印的工具。

代码片段

public final class LogFactory {

  //单例模式,不得自己new实例
  private LogFactory() {
    // disable construction
  }

  //根据传入的类来构建Log
  public static Log getLog(Class<?> aClass) {
    return getLog(aClass.getName());
  }

  //根据传入的类名来构建Log
  public static Log getLog(String logger) {
    try {
      //构造函数,参数必须是一个,为String型,指明logger的名称
      return logConstructor.newInstance(new Object[] { logger });
    } catch (Throwable t) {
      throw new LogException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
    }
  }
}
发布了60 篇原创文章 · 获赞 1 · 访问量 3341

猜你喜欢

转载自blog.csdn.net/qq_16438883/article/details/103482358