设计模式是解决问题的方案,从大神的代码中学习对设计模式的使用,可以有效提升个人编码及设计代码的能力。本系列博文用于总结阅读过的框架源码(Spring 系列、Mybatis)及 JDK 源码中 所使用过的设计模式,并结合个人工作经验,重新理解设计模式。

本篇博文主要看一下行为型的几个设计模式,即,策略模式、模板方法模式、迭代器模式、观察者模式 及 责任链模式。

策略模式

个人理解

去年看了蛮多源码,发现 框架的开发者在实际使用设计模式时,大都会根据实际情况 使用其变体,老老实实按照书上的类图及定义去设计代码的比较少。不过我们依然还是先看一下书上的定义,然后比较一下理论与实践的一些差别吧。策略模式的类图及定义如下。

avatar

定义一系列算法,封装每个算法 并使它们可以互换。该模式的主要角色如下:

  • Strategy 接口:用于定义一个算法族,它们都具有 behavior()方法;
  • Context:使用该算法的类,持有 Strategy 对象,其中的 setStrategy(Strategy stra)方法可以动态地改变 strategy 对象,以此改变自己所使用的算法。

很多书上都使用 Duck 和 QuackBehavior 作为示例进行说明,这里就不重复咯,主要看一下 Spring 中是如何使用该模式的。

Spring 中的实现

Spring 的 AbstractAutowireCapableBeanFactory 在进行 bean 实例化时使用了策略模式的变种,其中 InstantiationStrategy 接口 定义了实例化方法,实现类 SimpleInstantiationStrategy 和 CglibSubclassingInstantiationStrategy 分别实现了各自的算法,AbstractAutowireCapableBeanFactory 则通过持有 InstantiationStrategy 对象,对算进行使用。其源码实现如下。

  1. /**
  2. * 本接口用于定义bean实例的创建,通过给定的RootBeanDefinition对象
  3. * 本组件使用了策略模式,因为各种情况,需要使用不同的方法来实现,包括使用CGLIB动态创建子类
  4. * @author Rod Johnson
  5. * @since 1.1
  6. */
  7. public interface InstantiationStrategy {
  8. /**
  9. * 返回一个bean实例,使用BeanFactory给定的参数
  10. */
  11. Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner)
  12. throws BeansException;
  13. Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
  14. Constructor<?> ctor, Object[] args) throws BeansException;
  15. Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
  16. Object factoryBean, Method factoryMethod, Object[] args) throws BeansException;
  17. }
  18. public class SimpleInstantiationStrategy implements InstantiationStrategy {
  19. /**
  20. * 具体使用哪个策略进行bean的实例化,是在这个实现类中决定的
  21. */
  22. public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
  23. // 如果beanDefinition中没有方法覆盖,则使用Java的反射机制实例化对象,否则使用CGLIB策略
  24. if (beanDefinition.getMethodOverrides().isEmpty()) {
  25. Constructor<?> constructorToUse;
  26. synchronized (beanDefinition.constructorArgumentLock) {
  27. // 获取对象的构造方法或生成对象的工厂方法对bean进行实例化
  28. constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
  29. // 如果前面没有获取到构造方法,则通过反射获取
  30. if (constructorToUse == null) {
  31. // 使用JDK的反射机制,判断要实例化的Bean是否是接口
  32. final Class clazz = beanDefinition.getBeanClass();
  33. // 如果clazz是一个接口,直接抛出异常
  34. if (clazz.isInterface()) {
  35. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  36. }
  37. try {
  38. if (System.getSecurityManager() != null) {
  39. // 这里是一个匿名内置类,使用反射机制获取Bean的构造方法
  40. constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() {
  41. public Constructor run() throws Exception {
  42. return clazz.getDeclaredConstructor((Class[]) null);
  43. }
  44. });
  45. }
  46. else {
  47. constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
  48. }
  49. beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
  50. }
  51. catch (Exception ex) {
  52. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  53. }
  54. }
  55. }
  56. // 使用BeanUtils实例化,通过反射机制调用”构造方法.newInstance(arg)”来进行实例化
  57. return BeanUtils.instantiateClass(constructorToUse);
  58. }
  59. else {
  60. /**
  61. * !!!!!!!!!!!!!!
  62. * 使用CGLIB来实例化对象
  63. * 调用了其子类CglibSubclassingInstantiationStrategy中的实现
  64. * !!!!!!!!!!!!!!
  65. */
  66. return instantiateWithMethodInjection(beanDefinition, beanName, owner);
  67. }
  68. }
  69. }
  70. public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
  71. /**
  72. * 下面两个方法都通过实例化自己的私有静态内部类CglibSubclassCreator,
  73. * 然后调用该内部类对象的实例化方法instantiate()完成实例化
  74. */
  75. protected Object instantiateWithMethodInjection(
  76. RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
  77. // 必须生成cglib子类
  78. return new CglibSubclassCreator(beanDefinition, owner).instantiate(null, null);
  79. }
  80. @Override
  81. protected Object instantiateWithMethodInjection(
  82. RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
  83. Constructor ctor, Object[] args) {
  84. return new CglibSubclassCreator(beanDefinition, owner).instantiate(ctor, args);
  85. }
  86. /**
  87. * 为避免3.2之前的Spring版本中的外部cglib依赖而创建的内部类
  88. */
  89. private static class CglibSubclassCreator {
  90. private final RootBeanDefinition beanDefinition;
  91. private final BeanFactory owner;
  92. public CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner) {
  93. this.beanDefinition = beanDefinition;
  94. this.owner = owner;
  95. }
  96. //使用CGLIB进行Bean对象实例化
  97. public Object instantiate(Constructor ctor, Object[] args) {
  98. //实例化Enhancer对象,并为Enhancer对象设置父类,生成Java对象的参数,比如:基类、回调方法等
  99. Enhancer enhancer = new Enhancer();
  100. //将Bean本身作为其父类
  101. enhancer.setSuperclass(this.beanDefinition.getBeanClass());
  102. enhancer.setCallbackFilter(new CallbackFilterImpl());
  103. enhancer.setCallbacks(new Callback[] {
  104. NoOp.INSTANCE,
  105. new LookupOverrideMethodInterceptor(),
  106. new ReplaceOverrideMethodInterceptor()
  107. });
  108. //使用CGLIB的create方法生成实例对象
  109. return (ctor == null) ? enhancer.create() : enhancer.create(ctor.getParameterTypes(), args);
  110. }
  111. }
  112. }
  113. public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
  114. implements AutowireCapableBeanFactory {
  115. /** 创建bean实例的策略,注意 这里直接实例化的是 CglibSubclassingInstantiationStrategy 对象 */
  116. private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
  117. /**
  118. * 设置用于创建bean实例的实例化策略,默认使用CglibSubclassingInstantiationStrategy
  119. */
  120. public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
  121. this.instantiationStrategy = instantiationStrategy;
  122. }
  123. protected InstantiationStrategy getInstantiationStrategy() {
  124. return this.instantiationStrategy;
  125. }
  126. /**
  127. * 使用默认的无参构造方法实例化Bean对象
  128. */
  129. protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  130. try {
  131. Object beanInstance;
  132. final BeanFactory parent = this;
  133. // 获取系统的安全管理接口,JDK标准的安全管理API
  134. if (System.getSecurityManager() != null) {
  135. // 这里是一个匿名内置类,根据实例化策略创建实例对象
  136. beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
  137. public Object run() {
  138. return getInstantiationStrategy().instantiate(mbd, beanName, parent);
  139. }
  140. }, getAccessControlContext());
  141. }
  142. else {
  143. /**
  144. * !!!!!!!!!!!!!!
  145. * 使用初始化策略实例化Bean对象
  146. * !!!!!!!!!!!!!!
  147. */
  148. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
  149. }
  150. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  151. initBeanWrapper(bw);
  152. return bw;
  153. }
  154. catch (Throwable ex) {
  155. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  156. }
  157. }
  158. ...
  159. }

与标准的策略模式的设计区别在于,实现类 CglibSubclassingInstantiationStrategy 并不是直接实现了 InstantiationStrategy 接口,而是继承了 SimpleInstantiationStrategy,SimpleInstantiationStrategy 直接实现了 通过 JDK 反射机制实例化 bean 的策略,而 CglibSubclassingInstantiationStrategy 则是在自己的私有静态内部类中 完成的 通过 CGLIB 实例化 bean 的策略。

另外,虽然 AbstractAutowireCapableBeanFactory 默认持有的是 CglibSubclassingInstantiationStrategy 的实例,但具体使用哪个实现类中的策略,则是由 CglibSubclassingInstantiationStrategy 的父类 SimpleInstantiationStrategy 中的 instantiate()方法决定的。也就是说,虽然持有的是 CglibSubclassingInstantiationStrategy 对象,但实际上可能使用的是 JDK 反射机制实例化 bean 的策略。

设计模式的生产实践可能比 理论上的那些示例复杂的多,所以,若想确实提高自己代码的设计能力,还是要摆脱书本,多看实际应用。

Mybatis 中的实现

mybatis 的 DefaultSqlSession 使用了策略模式,DefaultSqlSession 扮演了 Context 的角色,Executor 接口及其实现类扮演了策略接口及实现。DefaultSqlSession 持有 Executor 对象,在 DefaultSqlSession 实例化时通过构造方法传入具体的 Executor 对象,根据持有的 Executor 对象的不同,而使用不同的策略进行数据库操作。具体使用哪个 Executor 的实例,由 Configuration 的 newExecutor() 方法决定。

  1. public class DefaultSqlSession implements SqlSession {
  2. private final Executor executor;
  3. /**
  4. * 在构造方法中为 executor 赋值,没有提供专门的set方法
  5. */
  6. public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
  7. this.configuration = configuration;
  8. this.executor = executor;
  9. this.dirty = false;
  10. this.autoCommit = autoCommit;
  11. }
  12. /**
  13. * executor的不同,决定了DefaultSqlSession使用哪种策略执行SQL操作
  14. */
  15. @Override
  16. public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
  17. try {
  18. MappedStatement ms = configuration.getMappedStatement(statement);
  19. executor.query(ms, wrapCollection(parameter), rowBounds, handler);
  20. } catch (Exception e) {
  21. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  22. } finally {
  23. ErrorContext.instance().reset();
  24. }
  25. }
  26. @Override
  27. public int update(String statement, Object parameter) {
  28. try {
  29. dirty = true;
  30. MappedStatement ms = configuration.getMappedStatement(statement);
  31. return executor.update(ms, wrapCollection(parameter));
  32. } catch (Exception e) {
  33. throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
  34. } finally {
  35. ErrorContext.instance().reset();
  36. }
  37. }
  38. }
  39. public interface Executor {
  40. int update(MappedStatement ms, Object parameter) throws SQLException;
  41. <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;
  42. void commit(boolean required) throws SQLException;
  43. void rollback(boolean required) throws SQLException;
  44. Transaction getTransaction();
  45. ......
  46. }
  47. public abstract class BaseExecutor implements Executor {
  48. ......
  49. protected BaseExecutor(Configuration configuration, Transaction transaction) {
  50. this.transaction = transaction;
  51. this.deferredLoads = new ConcurrentLinkedQueue<>();
  52. this.localCache = new PerpetualCache("LocalCache");
  53. this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
  54. this.closed = false;
  55. this.configuration = configuration;
  56. this.wrapper = this;
  57. }
  58. ......
  59. }
  60. public class SimpleExecutor extends BaseExecutor {
  61. public SimpleExecutor(Configuration configuration, Transaction transaction) {
  62. super(configuration, transaction);
  63. }
  64. @Override
  65. public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  66. Statement stmt = null;
  67. try {
  68. Configuration configuration = ms.getConfiguration();
  69. StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
  70. stmt = prepareStatement(handler, ms.getStatementLog());
  71. return handler.update(stmt);
  72. } finally {
  73. closeStatement(stmt);
  74. }
  75. }
  76. @Override
  77. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  78. Statement stmt = null;
  79. try {
  80. // 获取配置对象
  81. Configuration configuration = ms.getConfiguration();
  82. // 创建 StatementHandler 对象,实际返回的是 RoutingStatementHandler 对象,前面介绍过,
  83. // 其中根据 MappedStatement.statementType 选择具体的 StatementHandler 实现
  84. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
  85. // 完成 Statement 的创建和初始化,该方法首先会调用 StatementHandler.prepare() 方法
  86. // 创建 Statement 对象, 然后调用 StatementHandler. parameterize() 方法处理占位符
  87. stmt = prepareStatement(handler, ms.getStatementLog());
  88. // 调用 StatementHandler.query() 方法,执行 SQL 语句,并通过 ResultSetHandler 完成
  89. // 结果集的映射
  90. return handler.query(stmt, resultHandler);
  91. } finally {
  92. // 关闭 Statement 对象
  93. closeStatement(stmt);
  94. }
  95. }
  96. ......
  97. }
  98. public class BatchExecutor extends BaseExecutor {
  99. @Override
  100. public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  101. // 获取配置对象
  102. final Configuration configuration = ms.getConfiguration();
  103. // 创建 StatementHandler 对象
  104. final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  105. final BoundSql boundSql = handler.getBoundSql();
  106. // 获取 SQL 语句
  107. final String sql = boundSql.getSql();
  108. final Statement stmt;
  109. // 如果当前执行的 SQL 模式与上次执行的 SQL 模式相同且对应的 MappedStatement 对象相同
  110. if (sql.equals(currentSql) && ms.equals(currentStatement)) {
  111. // 获取 statementList 集合中最后一个 Statement 对象
  112. int last = statementList.size() - 1;
  113. stmt = statementList.get(last);
  114. applyTransactionTimeout(stmt);
  115. // 绑定实参,处理占位符 “?”
  116. handler.parameterize(stmt);//fix Issues 322
  117. // 查找对应的 BatchResult 对象,并记录用户传入的实参
  118. BatchResult batchResult = batchResultList.get(last);
  119. batchResult.addParameterObject(parameterObject);
  120. } else {
  121. Connection connection = getConnection(ms.getStatementLog());
  122. // 创建新的 Statement 对象
  123. stmt = handler.prepare(connection, transaction.getTimeout());
  124. // 绑定实参,处理占位符“?”
  125. handler.parameterize(stmt); //fix Issues 322
  126. // 更新 currentSql 和 currentStatement
  127. currentSql = sql;
  128. currentStatement = ms;
  129. // 将新创建的 Statement 对象添加到 statementList 集合中
  130. statementList.add(stmt);
  131. // 添加新的 BatchResult 对象
  132. batchResultList.add(new BatchResult(ms, sql, parameterObject));
  133. }
  134. // 底层通过调用 Statement.addBatch() 方法添加 SQL 语句
  135. handler.batch(stmt);
  136. return BATCH_UPDATE_RETURN_VALUE;
  137. }
  138. ......
  139. }
  140. public class Configuration {
  141. /**
  142. * 在这个方法中决定使用哪个 Executor 实现
  143. */
  144. public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
  145. executorType = executorType == null ? defaultExecutorType : executorType;
  146. executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
  147. Executor executor;
  148. if (ExecutorType.BATCH == executorType) {
  149. executor = new BatchExecutor(this, transaction);
  150. } else if (ExecutorType.REUSE == executorType) {
  151. executor = new ReuseExecutor(this, transaction);
  152. } else {
  153. executor = new SimpleExecutor(this, transaction);
  154. }
  155. if (cacheEnabled) {
  156. executor = new CachingExecutor(executor);
  157. }
  158. executor = (Executor) interceptorChain.pluginAll(executor);
  159. return executor;
  160. }
  161. ......
  162. }

模板方法模式

个人理解

在该模式中,一个算法可以分为多个步骤,这些步骤的执行次序在一个被称为“模板方法”的方法中定义,而算法的每个步骤都对应着一个方法,这些方法被称为 “基本方法”。 模板方法按照它定义的顺序依次调用多个基本方法,从而实现整个算法流程。在模板方法模式中,会将模板方法的实现以及那些固定不变的基本方法的实现放在父类中,而那些不固定的基 本方法在父类中只是抽象方法,其真正的实现代码会被延迟到子类中完成。

我觉得这是最简单且常用的设计模式之一咯,自己在实现一些功能时也会使用这种模式,在抽象类中定义好流程的执行顺序,通用的流程在抽象类中实现,个性化的流程交给各个子类去实现。spring 及 mybatis 中均有应用。

Spring 中的应用

Spring 中的 AbstractApplicationContext 和其子类 AbstractRefreshableApplicationContext、GenericApplicationContext 使用了模板方法模式。源码实现及详细注释如下。

  1. public abstract class AbstractApplicationContext extends DefaultResourceLoader
  2. implements ConfigurableApplicationContext, DisposableBean {
  3. /**
  4. * 告诉子类启动refreshBeanFactory()方法,BeanDefinition资源文件的载入
  5. * 从子类的refreshBeanFactory()方法启动开始
  6. */
  7. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  8. // 这里使用了模板方法模式,自己定义了流程,个性化的方法实现交由子类完成
  9. // 其中,refreshBeanFactory() 和 getBeanFactory()为抽象方法
  10. refreshBeanFactory();
  11. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  12. if (logger.isDebugEnabled()) {
  13. logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
  14. }
  15. return beanFactory;
  16. }
  17. protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
  18. public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
  19. }
  20. public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
  21. /**
  22. * 在这里完成了容器的初始化,并赋值给自己private的beanFactory属性,为下一步调用做准备
  23. * 从父类AbstractApplicationContext继承的抽象方法,自己做了实现
  24. */
  25. @Override
  26. protected final void refreshBeanFactory() throws BeansException {
  27. // 如果已经建立了IoC容器,则销毁并关闭容器
  28. if (hasBeanFactory()) {
  29. destroyBeans();
  30. closeBeanFactory();
  31. }
  32. try {
  33. // 创建IoC容器,DefaultListableBeanFactory类实现了ConfigurableListableBeanFactory接口
  34. DefaultListableBeanFactory beanFactory = createBeanFactory();
  35. beanFactory.setSerializationId(getId());
  36. // 定制化IoC容器,如设置启动参数,开启注解的自动装配等
  37. customizeBeanFactory(beanFactory);
  38. // 载入BeanDefinition,这里又使用了一个委派模式,在当前类定义此抽象方法,子类容器具体实现
  39. loadBeanDefinitions(beanFactory);
  40. synchronized (this.beanFactoryMonitor) {
  41. // 给自己的属性赋值
  42. this.beanFactory = beanFactory;
  43. }
  44. }
  45. catch (IOException ex) {
  46. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  47. }
  48. }
  49. @Override
  50. public final ConfigurableListableBeanFactory getBeanFactory() {
  51. synchronized (this.beanFactoryMonitor) {
  52. if (this.beanFactory == null) {
  53. throw new IllegalStateException("BeanFactory not initialized or already closed - " +
  54. "call 'refresh' before accessing beans via the ApplicationContext");
  55. }
  56. return this.beanFactory;
  57. }
  58. }
  59. }
  60. public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
  61. @Override
  62. protected final void refreshBeanFactory() throws IllegalStateException {
  63. if (this.refreshed) {
  64. throw new IllegalStateException(
  65. "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
  66. }
  67. this.beanFactory.setSerializationId(getId());
  68. this.refreshed = true;
  69. }
  70. public final ConfigurableListableBeanFactory getBeanFactory() {
  71. return this.beanFactory;
  72. }
  73. }

Mybatis 中的应用

mybatis 的 Executor 组件使用了该模式,其中抽象类 BaseExecutor 定义了模板方法和抽象方法,实现类 SimpleExecutor、BatchExecutor 及 ReuseExecutor 对抽象方法进行具体实现。源码如下。

  1. public abstract class BaseExecutor implements Executor {
  2. @Override
  3. public int update(MappedStatement ms, Object parameter) throws SQLException {
  4. ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
  5. // 判断当前 Executor 是否已经关闭
  6. if (closed) {
  7. throw new ExecutorException("Executor was closed.");
  8. }
  9. // clearLocalCache() 方法中会调用 localCache()、localOutputParameterCache() 两个
  10. // 缓存的 clear() 方法完成清理工作。这是影响一级缓存中数据存活时长的第三个方面
  11. clearLocalCache();
  12. // 调用 doUpdate() 抽象方法执行 SQL 语句
  13. return doUpdate(ms, parameter);
  14. }
  15. public List<BatchResult> flushStatements(boolean isRollBack) throws SQLException {
  16. // 判断当前 Executor 是否已经关闭
  17. if (closed) {
  18. throw new ExecutorException("Executor was closed.");
  19. }
  20. // 调用抽象方法 doFlushStatements(),其参数 isRollBack 表示是否执行 Executor 中缓存的
  21. // SQL 语句,false 表示执行,true 表示不执行
  22. return doFlushStatements(isRollBack);
  23. }
  24. /**
  25. * 调用 doQuery() 方法完成数据库查询,并得到映射后的结果集对象,
  26. */
  27. private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  28. List<E> list;
  29. // 在缓存中添加占位符
  30. localCache.putObject(key, EXECUTION_PLACEHOLDER);
  31. try {
  32. // 调用 doQuery() 抽象方法,完成数据库查询操作,并返回结果集对象
  33. list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
  34. } finally {
  35. // 删除占位符
  36. localCache.removeObject(key);
  37. }
  38. // 将真正的结采对象添加到一级缓存中
  39. localCache.putObject(key, list);
  40. // 是否为存储过程调用
  41. if (ms.getStatementType() == StatementType.CALLABLE) {
  42. // 缓存输出类型的参数
  43. localOutputParameterCache.putObject(key, parameter);
  44. }
  45. return list;
  46. }
  47. @Override
  48. public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException {
  49. BoundSql boundSql = ms.getBoundSql(parameter);
  50. return doQueryCursor(ms, parameter, rowBounds, boundSql);
  51. }
  52. protected abstract int doUpdate(MappedStatement ms, Object parameter)
  53. throws SQLException;
  54. protected abstract List<BatchResult> doFlushStatements(boolean isRollback)
  55. throws SQLException;
  56. protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
  57. throws SQLException;
  58. protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql)
  59. throws SQLException;
  60. }
  61. public class SimpleExecutor extends BaseExecutor {
  62. @Override
  63. public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  64. Statement stmt = null;
  65. try {
  66. Configuration configuration = ms.getConfiguration();
  67. StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
  68. stmt = prepareStatement(handler, ms.getStatementLog());
  69. return handler.update(stmt);
  70. } finally {
  71. closeStatement(stmt);
  72. }
  73. }
  74. @Override
  75. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  76. Statement stmt = null;
  77. try {
  78. // 获取配置对象
  79. Configuration configuration = ms.getConfiguration();
  80. // 创建 StatementHandler 对象,实际返回的是 RoutingStatementHandler 对象,前面介绍过,
  81. // 其中根据 MappedStatement.statementType 选择具体的 StatementHandler 实现
  82. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
  83. // 完成 Statement 的创建和初始化,该方法首先会调用 StatementHandler.prepare() 方法
  84. // 创建 Statement 对象, 然后调用 StatementHandler. parameterize() 方法处理占位符
  85. stmt = prepareStatement(handler, ms.getStatementLog());
  86. // 调用 StatementHandler.query() 方法,执行 SQL 语句,并通过 ResultSetHandler 完成
  87. // 结果集的映射
  88. return handler.query(stmt, resultHandler);
  89. } finally {
  90. // 关闭 Statement 对象
  91. closeStatement(stmt);
  92. }
  93. }
  94. @Override
  95. protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
  96. Configuration configuration = ms.getConfiguration();
  97. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
  98. Statement stmt = prepareStatement(handler, ms.getStatementLog());
  99. Cursor<E> cursor = handler.queryCursor(stmt);
  100. stmt.closeOnCompletion();
  101. return cursor;
  102. }
  103. @Override
  104. public List<BatchResult> doFlushStatements(boolean isRollback) {
  105. return Collections.emptyList();
  106. }
  107. private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
  108. Statement stmt;
  109. Connection connection = getConnection(statementLog);
  110. stmt = handler.prepare(connection, transaction.getTimeout());
  111. handler.parameterize(stmt);
  112. return stmt;
  113. }
  114. }
  115. public class BatchExecutor extends BaseExecutor {
  116. @Override
  117. public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  118. // 获取配置对象
  119. final Configuration configuration = ms.getConfiguration();
  120. // 创建 StatementHandler 对象
  121. final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  122. final BoundSql boundSql = handler.getBoundSql();
  123. // 获取 SQL 语句
  124. final String sql = boundSql.getSql();
  125. final Statement stmt;
  126. // 如果当前执行的 SQL 模式与上次执行的 SQL 模式相同且对应的 MappedStatement 对象相同
  127. if (sql.equals(currentSql) && ms.equals(currentStatement)) {
  128. // 获取 statementList 集合中最后一个 Statement 对象
  129. int last = statementList.size() - 1;
  130. stmt = statementList.get(last);
  131. applyTransactionTimeout(stmt);
  132. // 绑定实参,处理占位符 “?”
  133. handler.parameterize(stmt);//fix Issues 322
  134. // 查找对应的 BatchResult 对象,并记录用户传入的实参
  135. BatchResult batchResult = batchResultList.get(last);
  136. batchResult.addParameterObject(parameterObject);
  137. } else {
  138. Connection connection = getConnection(ms.getStatementLog());
  139. // 创建新的 Statement 对象
  140. stmt = handler.prepare(connection, transaction.getTimeout());
  141. // 绑定实参,处理占位符“?”
  142. handler.parameterize(stmt); //fix Issues 322
  143. // 更新 currentSql 和 currentStatement
  144. currentSql = sql;
  145. currentStatement = ms;
  146. // 将新创建的 Statement 对象添加到 statementList 集合中
  147. statementList.add(stmt);
  148. // 添加新的 BatchResult 对象
  149. batchResultList.add(new BatchResult(ms, sql, parameterObject));
  150. }
  151. // 底层通过调用 Statement.addBatch() 方法添加 SQL 语句
  152. handler.batch(stmt);
  153. return BATCH_UPDATE_RETURN_VALUE;
  154. }
  155. @Override
  156. public <E> List<E> doQuery(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
  157. throws SQLException {
  158. Statement stmt = null;
  159. try {
  160. flushStatements();
  161. Configuration configuration = ms.getConfiguration();
  162. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameterObject, rowBounds, resultHandler, boundSql);
  163. Connection connection = getConnection(ms.getStatementLog());
  164. stmt = handler.prepare(connection, transaction.getTimeout());
  165. handler.parameterize(stmt);
  166. return handler.query(stmt, resultHandler);
  167. } finally {
  168. closeStatement(stmt);
  169. }
  170. }
  171. @Override
  172. protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
  173. flushStatements();
  174. Configuration configuration = ms.getConfiguration();
  175. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
  176. Connection connection = getConnection(ms.getStatementLog());
  177. Statement stmt = handler.prepare(connection, transaction.getTimeout());
  178. handler.parameterize(stmt);
  179. Cursor<E> cursor = handler.queryCursor(stmt);
  180. stmt.closeOnCompletion();
  181. return cursor;
  182. }
  183. @Override
  184. public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
  185. try {
  186. // results 集合用于储存批处理的结采
  187. List<BatchResult> results = new ArrayList<>();
  188. // 如果明确指定了要回滚事务,则直接返回空集合,忽略 statementList 集合中记录的 SQL 语句
  189. if (isRollback) {
  190. return Collections.emptyList();
  191. }
  192. // 遍历 statementList 集合
  193. for (int i = 0, n = statementList.size(); i < n; i++) {
  194. // 获取 Statement 对象
  195. Statement stmt = statementList.get(i);
  196. applyTransactionTimeout(stmt);
  197. // 获取对应 BatchResult 对象
  198. BatchResult batchResult = batchResultList.get(i);
  199. try {
  200. // 调用 Statement.executeBatch() 方法批量执行其中记录的 SQL 语句,并使用返回的 int 数组
  201. // 更新 BatchResult.updateCounts 字段,其中每一个元素都表示一条 SQL 语句影响的记录条数
  202. batchResult.setUpdateCounts(stmt.executeBatch());
  203. MappedStatement ms = batchResult.getMappedStatement();
  204. List<Object> parameterObjects = batchResult.getParameterObjects();
  205. // 获取配置的 KeyGenerator 对象
  206. KeyGenerator keyGenerator = ms.getKeyGenerator();
  207. if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
  208. Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
  209. // 获取数据库生成的主键,并设置到 parameterObjects 中,前面已经分析过,这里不再重复
  210. jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
  211. } else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141
  212. // 对于其他类型的 KeyGenerator,会调用其 processAfter() 方法
  213. for (Object parameter : parameterObjects) {
  214. keyGenerator.processAfter(this, ms, stmt, parameter);
  215. }
  216. }
  217. // Close statement to close cursor #1109
  218. closeStatement(stmt);
  219. } catch (BatchUpdateException e) {
  220. StringBuilder message = new StringBuilder();
  221. message.append(batchResult.getMappedStatement().getId())
  222. .append(" (batch index #")
  223. .append(i + 1)
  224. .append(")")
  225. .append(" failed.");
  226. if (i > 0) {
  227. message.append(" ")
  228. .append(i)
  229. .append(" prior sub executor(s) completed successfully, but will be rolled back.");
  230. }
  231. throw new BatchExecutorException(message.toString(), e, results, batchResult);
  232. }
  233. // 添加 BatchResult 到 results 集合
  234. results.add(batchResult);
  235. }
  236. return results;
  237. } finally {
  238. // 关闭所有 Statement 对象,并清空 currentSql 字段、清空 statementList 集合、
  239. // 清空 batchResultList 集合(略)
  240. for (Statement stmt : statementList) {
  241. closeStatement(stmt);
  242. }
  243. currentSql = null;
  244. statementList.clear();
  245. batchResultList.clear();
  246. }
  247. }
  248. }
  249. public class ReuseExecutor extends BaseExecutor {
  250. @Override
  251. public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  252. Configuration configuration = ms.getConfiguration();
  253. StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
  254. Statement stmt = prepareStatement(handler, ms.getStatementLog());
  255. return handler.update(stmt);
  256. }
  257. @Override
  258. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  259. Configuration configuration = ms.getConfiguration();
  260. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
  261. Statement stmt = prepareStatement(handler, ms.getStatementLog());
  262. return handler.query(stmt, resultHandler);
  263. }
  264. @Override
  265. protected <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException {
  266. Configuration configuration = ms.getConfiguration();
  267. StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, null, boundSql);
  268. Statement stmt = prepareStatement(handler, ms.getStatementLog());
  269. return handler.queryCursor(stmt);
  270. }
  271. @Override
  272. public List<BatchResult> doFlushStatements(boolean isRollback) {
  273. for (Statement stmt : statementMap.values()) {
  274. closeStatement(stmt);
  275. }
  276. statementMap.clear();
  277. return Collections.emptyList();
  278. }
  279. }

可以看得出来,模板方法就是 BaseExecutor 的 update()、flushStatements()、queryFromDatabase() 及 queryCursor(),分别使用了抽象方法 doUpdate()、doFlushStatements()、doQuery() 及 doQueryCursor()。

迭代器模式

个人理解

这个模式最经典的实现莫过于 Java 的集合类咯。同样还是先简单介绍一下这个设计模式,然后结合 ArrayList 的源码进行分析。

本设计模式用于提供一种遍历集合元素的方法,且不暴露集合对象的内部表示。其主要角色 和 简单实现如下:

  • Aggregate:聚合类,有一个可以获取 Iterator 对象的 iterator() 方法;
  • Iterator:主要定义了 hasNest() 和 next()方法;
  1. public interface Aggregate {
  2. Iterator iterator();
  3. }
  4. public class ConcreteAggregate implements Aggregate {
  5. private Integer[] elements;
  6. public ConcreteAggregate() {
  7. elements = new Integer[10];
  8. for (int i = 0; i < elements.length; i++) {
  9. elements[i] = i;
  10. }
  11. }
  12. @Override
  13. public Iterator iterator() {
  14. return new ConcreteIterator(elements);
  15. }
  16. }
  17. public interface Iterator<Integer> {
  18. boolean hasNext();
  19. Integer next();
  20. }
  21. public class ConcreteIterator<Integer> implements Iterator {
  22. private Integer[] elements;
  23. private int position = 0;
  24. public ConcreteIterator(Integer[] elements) {
  25. this.elements = elements;
  26. }
  27. @Override
  28. public boolean hasNext() {
  29. return position < elements.length;
  30. }
  31. @Override
  32. public Integer next() {
  33. return elements[position ++];
  34. }
  35. }
  36. public class Client {
  37. public static void main(String[] args) {
  38. Aggregate aggregate = new ConcreteAggregate();
  39. Iterator<Integer> iterator = aggregate.iterator();
  40. while (iterator.hasNext()) {
  41. System.out.println(iterator.next());
  42. }
  43. }
  44. }

ArrayList 对迭代器模式的实现

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  3. /**
  4. * 存储ArrayList元素的数组缓冲区。ArrayList的容量是此数组缓冲区的长度
  5. */
  6. transient Object[] elementData; // non-private to simplify nested class access
  7. /**
  8. * ArrayList的大小(其包含的元素数)
  9. */
  10. private int size;
  11. /**
  12. * 以正确的顺序返回此列表中元素的迭代器
  13. */
  14. public Iterator<E> iterator() {
  15. return new Itr();
  16. }
  17. /**
  18. * ArrayList的私有内部类,其实现了Iterator接口,所以也是一个迭代器
  19. * AbstractList.Itr的优化版本
  20. */
  21. private class Itr implements Iterator<E> {
  22. int cursor; // 要返回的下一个元素的索引
  23. int lastRet = -1; // 返回的最后一个元素的索引;如果没有则返回 -1
  24. int expectedModCount = modCount;
  25. public boolean hasNext() {
  26. return cursor != size;
  27. }
  28. @SuppressWarnings("unchecked")
  29. public E next() {
  30. checkForComodification();
  31. int i = cursor;
  32. if (i >= size)
  33. throw new NoSuchElementException();
  34. Object[] elementData = ArrayList.this.elementData;
  35. if (i >= elementData.length)
  36. throw new ConcurrentModificationException();
  37. cursor = i + 1;
  38. return (E) elementData[lastRet = i];
  39. }
  40. }
  41. }

观察者模式

个人理解

这个模式也是平时很少使用的,所以就简单介绍一下,然后结合 JDK 中的源码加深理解。该模式用于定义对象之间的一对多依赖,当一个对象状态改变时,它的所有依赖都会收到通知,然后自动更新。类图和主要角色如下:

avatar

  • Subject 主题:具有注册、移除及通知观察者的功能,主题是通过维护一个观察者列表来实现这些功能的;
  • Observer 观察者:其注册需要 Subject 的 registerObserver()方法。

JDK 中的源码实现

java.util 包中提供了 Observable 类和 Observer 接口,其中要求,被观察者需要继承 Observable 类,观察则需要实现 Observer 接口。下面看一下其源码实现。

  1. /**
  2. * 当一个类希望获知 所观察的对象的变化时,可以通过实现本接口来完成
  3. * 而被观察的对象则需要继承 Observable 类
  4. * @author Chris Warth
  5. * @see java.util.Observable
  6. * @since JDK1.0
  7. */
  8. public interface Observer {
  9. /**
  10. * 每当所观察的对象发生更改时,此方法都会被调用。应用程序调用Observable对象的
  11. * notifyObservators()方法时,将通知所有注册的观察者 本对象(被观察者)已更新
  12. */
  13. void update(Observable o, Object arg);
  14. }
  15. /**
  16. * 这个类表示一个可被观察的对象,或者模型视图范例中的“数据”。它可以被继承,
  17. * 以表示该类 可以被观察到。
  18. * 一个Observable对象可以有一个或多个观察者,观察者可以是实现了Observer接口的任何对象。
  19. * 在一个Observable实例更改之后,调用其notifyObservers()方法,该方法可以通过调用 所有
  20. * 已注册的Observer对象的update()方法通知其所有观察者,被观察的对象已更新。
  21. * @author Chris Warth
  22. * @see java.util.Observable#notifyObservers()
  23. * @see java.util.Observable#notifyObservers(java.lang.Object)
  24. * @see java.util.Observer
  25. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  26. * @since JDK1.0
  27. */
  28. public class Observable {
  29. private boolean changed = false;
  30. /**
  31. * 通过一个Vector来维护 观察者列表。
  32. * 由于该集合主要涉及元素的增删操作,所以个人认为使用LinkedList
  33. * 效果会更好一下
  34. */
  35. private Vector<Observer> obs;
  36. public Observable() {
  37. obs = new Vector<>();
  38. }
  39. /**
  40. * 注册 观察者对象
  41. */
  42. public synchronized void addObserver(Observer o) {
  43. if (o == null)
  44. throw new NullPointerException();
  45. if (!obs.contains(o)) {
  46. obs.addElement(o);
  47. }
  48. }
  49. /**
  50. * 移除观察者对象
  51. */
  52. public synchronized void deleteObserver(Observer o) {
  53. obs.removeElement(o);
  54. }
  55. public void notifyObservers() {
  56. notifyObservers(null);
  57. }
  58. /**
  59. * 如果此对象已更改,则通知其所有观察者,然后调用clearChanged()方法 清除更改标记
  60. */
  61. public void notifyObservers(Object arg) {
  62. // 一个临时数组缓冲区,用作当前观察者状态的快照
  63. Object[] arrLocal;
  64. synchronized (this) {
  65. if (!changed)
  66. return;
  67. arrLocal = obs.toArray();
  68. clearChanged();
  69. }
  70. for (int i = arrLocal.length-1; i>=0; i--)
  71. ((Observer)arrLocal[i]).update(this, arg);
  72. }
  73. /**
  74. * 清除观察者列表,使此对象不再具有任何观察者
  75. */
  76. public synchronized void deleteObservers() {
  77. obs.removeAllElements();
  78. }
  79. /**
  80. * 将本对象标记为已更改
  81. */
  82. protected synchronized void setChanged() {
  83. changed = true;
  84. }
  85. /**
  86. * 清除本对象的更改标准
  87. */
  88. protected synchronized void clearChanged() {
  89. changed = false;
  90. }
  91. /**
  92. * 查看本对象是否已更改
  93. */
  94. public synchronized boolean hasChanged() {
  95. return changed;
  96. }
  97. /**
  98. * 返回观察者列表的长度
  99. */
  100. public synchronized int countObservers() {
  101. return obs.size();
  102. }
  103. }

责任链模式

一般用在消息请求的处理上,如 Netty 的 ChannelHandler 组件,Tomcat 对 HTTP 请求的处理。我们当然可以将 请求的处理逻辑都写在一个类中,但这个类会非常雕肿且不易于维护,不符合开发封闭原则。

在责任链模式中,将上述臃肿的请求处理逻辑 拆分到多个 功能逻辑单一的 Handler 处理类中,这样我们就可以根据业务需求,将多个 Handler 对象组合成一条责任链,实现请求的处理。在一条责任链中,每个 Handler 对象 都包含对下一个 Handler 对象 的引用,一个 Handler 对象 处理完请求消息(或不能处理该请求)时, 会把请求传给下一个 Handler 对象 继续处理,依此类推,直至整条责任链结束。简单看一下责任链模式的类图。

avatar

Netty 中的应用

在 Netty 中,将 Channel 的数据管道抽象为 ChannelPipeline,消息在 ChannelPipeline 中流动和传递。ChannelPipeline 是 ChannelHandler 的容器,持有 I/O 事件拦截器 ChannelHandler 的链表,负责对 ChannelHandler 的管理和调度。由 ChannelHandler 对 I/O 事件 进行拦截和处理,并可以通过接口方便地新增和删除 ChannelHandler 来实现不同业务逻辑的处理。下图是 ChannelPipeline 源码中描绘的责任链事件处理过程。 avatar 其具体过程处理如下:

  1. 底层 SocketChannel 的 read 方法 读取 ByteBuf,触发 ChannelRead 事件,由 I/O 线程 NioEventLoop 调用 ChannelPipeline 的 fireChannelRead()方法,将消息传输到 ChannelPipeline 中。

  2. 消息依次被 InboundHandler 1、InboundHandler 2 … InboundHandler N 拦截处理,在这个过程中,任何 ChannelHandler 都可以中断当前的流程,结束消息的传递。

  3. 当调用 ChannelHandlerContext 的 write()方法 发送消息,消息从 OutbountHandler 1 开始 一直到 OutboundHandler N,最终被添加到消息发送缓冲区中等待刷新和发送。

在 Netty 中将事件根据源头的不同分为 InBound 事件 和 OutBound 事件。InBound 事件 通常由 I/O 线程 触发,例如 TCP 链路 建立和关闭、读事件等等,分别会触发相应的事件方法。而 OutBound 事件 则一般由用户主动发起的 网络 I/O 操作,例如用户发起的连接操作,绑定操作和消息发送操作等,也会分别触发相应的事件方法。由于 netty 中提供了一个抽象类 ChannelHandlerAdapter,它默认不处理拦截的事件。所以,在实际编程过程中,我们只需要继承 ChannelHandlerAdapter,在我们的 自定义 Handler 中覆盖业务关心的事件方法即可。其源码如下。

  1. /**
  2. * 它扮演了 责任链模式中的 Client角色,持有 构造 并使用 ChannelHandler责任链
  3. */
  4. public interface ChannelPipeline
  5. extends ChannelInboundInvoker, ChannelOutboundInvoker, Iterable<Entry<String, ChannelHandler>> {
  6. ChannelPipeline addFirst(EventExecutorGroup group, String name, ChannelHandler handler);
  7. ChannelPipeline addLast(String name, ChannelHandler handler);
  8. ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler);
  9. ChannelPipeline addFirst(ChannelHandler... handlers);
  10. ChannelPipeline addFirst(EventExecutorGroup group, ChannelHandler... handlers);
  11. ChannelPipeline addLast(ChannelHandler... handlers);
  12. ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);
  13. ChannelPipeline remove(ChannelHandler handler);
  14. ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler);
  15. ChannelHandler get(String name);
  16. @Override
  17. ChannelPipeline fireChannelRegistered();
  18. @Override
  19. ChannelPipeline fireChannelUnregistered();
  20. @Override
  21. ChannelPipeline fireChannelActive();
  22. @Override
  23. ChannelPipeline fireChannelInactive();
  24. @Override
  25. ChannelPipeline fireExceptionCaught(Throwable cause);
  26. @Override
  27. ChannelPipeline fireUserEventTriggered(Object event);
  28. @Override
  29. ChannelPipeline fireChannelRead(Object msg);
  30. @Override
  31. ChannelPipeline fireChannelReadComplete();
  32. @Override
  33. ChannelPipeline fireChannelWritabilityChanged();
  34. }
  35. /**
  36. * ChannelHandler本身并不是链式结构的,链式结构是交由 ChannelHandlerContext
  37. * 进行维护的
  38. */
  39. public interface ChannelHandler {
  40. void handlerAdded(ChannelHandlerContext ctx) throws Exception;
  41. void handlerRemoved(ChannelHandlerContext ctx) throws Exception;
  42. void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception;x
  43. }
  44. /**
  45. * DefaultChannelHandlerContext 持有一个 final 的 ChannelHandler对象,
  46. * 其父类 AbstractChannelHandlerContext 是一个双向链表的结构设计,这样就保证了
  47. * ChannelHandler 的 责任链式处理
  48. */
  49. final class DefaultChannelHandlerContext extends AbstractChannelHandlerContext {
  50. private final ChannelHandler handler;
  51. DefaultChannelHandlerContext(
  52. DefaultChannelPipeline pipeline, EventExecutor executor, String name, ChannelHandler handler) {
  53. super(pipeline, executor, name, isInbound(handler), isOutbound(handler));
  54. if (handler == null) {
  55. throw new NullPointerException("handler");
  56. }
  57. this.handler = handler;
  58. }
  59. @Override
  60. public ChannelHandler handler() {
  61. return handler;
  62. }
  63. private static boolean isInbound(ChannelHandler handler) {
  64. return handler instanceof ChannelInboundHandler;
  65. }
  66. private static boolean isOutbound(ChannelHandler handler) {
  67. return handler instanceof ChannelOutboundHandler;
  68. }
  69. }
  70. /**
  71. * 很容易看出来,这是一个双向链表的结构设计
  72. */
  73. abstract class AbstractChannelHandlerContext extends DefaultAttributeMap
  74. implements ChannelHandlerContext, ResourceLeakHint {
  75. private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannelHandlerContext.class);
  76. volatile AbstractChannelHandlerContext next;
  77. volatile AbstractChannelHandlerContext prev;
  78. ......
  79. }