跳至主要內容

Decorator Design Pattern

ChenSino原创设计模式小于 1 分钟

定义

装饰者模式是一种常用的设计模式,它动态地给一个对象添加一些额外的职责1。装饰者模式可以在不改变一个对象本身功能的基础上给对象增加额外的新行为2。

框架中使用

mybatis中:

打开sqlSession时,会创建Executor,最终会进入org.apache.ibatis.session.Configuration#newExecutor(org.apache.ibatis.transaction.Transaction, org.apache.ibatis.session.ExecutorType)

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    return (Executor) interceptorChain.pluginAll(executor);
  }

可以看到CachingExecutor里面包装了executor(默认是SimpleExecutor类型),只不过是在不改变原对象基础上加了缓存功能,CachingExecutor源码如下:


public class CachingExecutor implements Executor {

  private final Executor delegate;
  //增加了缓存管理
  private final TransactionalCacheManager tcm = new TransactionalCacheManager();

  public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    //从方法命名也可看出这是一个装饰者模式,wrapper,decorator等都可以翻译为装饰
    delegate.setExecutorWrapper(this);
  }

  @Override
  public Transaction getTransaction() {
    return delegate.getTransaction();
  }

  //略……
}