【从优秀源码中学习设计模式】--- 装饰者模式

前言

本文以Java语言为主,分析包括JDK、Spring、MyBatis、Guava等一些优秀的开源代码、项目,在这些开源代码、项目中都包含了大量的设计模式,通过对它们进行分析,能够快速帮助我们学会设计模式的使用方式,由理论过渡到实践中,进而真正了解设计模式的思想,由于内容较多,所以每个设计模式单独写一篇文章,需要了解其他模式请点击对应链接跳转。

建造者模式
适配器模式
策略模式
模板模式

装饰者模式

JDK

JDK中典型的装饰者模式就是其IO库中提供的字节流相关的类了,比如一般我们读写文件可能会这样写

// 基于字节流
InputStream is = new BufferedInputStream(new FileInputStream(new File("/xxx.txt")));
// 基于字符流
BufferedReader br = new BufferedReader(new FileReader("/xxx.txt"));

为了更好的支持多种读写文件的方式,通过使用装饰者模式,让使用者可以灵活、多变的选择读写文件的功能,从而实现对功能的各种增强。

MyBatis

MyBatis在构建二级缓存对象时,由于二级缓存对象的属性有很多,并且支持动态设置,所以选择了使用装饰者模式来实现

  public Cache build() {
    
    
    setDefaultImplementations();
    Cache cache = newBaseCacheInstance(implementation, id);
    setCacheProperties(cache);
    if (PerpetualCache.class.equals(cache.getClass())) {
    
    
      for (Class<? extends Cache> decorator : decorators) {
    
    
        cache = newCacheDecoratorInstance(decorator, cache);
        setCacheProperties(cache);
      }
      // 通过装饰器方式,为缓存添加功能
      cache = setStandardDecorators(cache);
    } else if (!LoggingCache.class.isAssignableFrom(cache.getClass())) {
    
    
      cache = new LoggingCache(cache);
    }
    return cache;
  }
  private Cache setStandardDecorators(Cache cache) {
    
    
    try {
    
    
      MetaObject metaCache = SystemMetaObject.forObject(cache);
      if (size != null && metaCache.hasSetter("size")) {
    
    
        metaCache.setValue("size", size);
      }
      if (clearInterval != null) {
    
    
        cache = new ScheduledCache(cache);
        ((ScheduledCache) cache).setClearInterval(clearInterval);
      }
      if (readWrite) {
    
    
        cache = new SerializedCache(cache);
      }
      cache = new LoggingCache(cache);
      cache = new SynchronizedCache(cache);
      if (blocking) {
    
    
        cache = new BlockingCache(cache);
      }
      return cache;
    } catch (Exception e) {
    
    
      throw new CacheException("Error building standard cache decorators.  Cause: " + e, e);
    }
  }

看看ScheduledCache、LoggingCache、SynchronizedCache等都拥有一个Cache对象。
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

Spring

Spring中的TransactionAwareCacheDecorator从名字也看出来了是运用了装饰器模式,增加了缓存对事物的支持

public class TransactionAwareCacheDecorator implements Cache {
    
    
    private final Cache targetCache;

    public TransactionAwareCacheDecorator(Cache targetCache) {
    
    
        Assert.notNull(targetCache, "Target Cache must not be null");
        this.targetCache = targetCache;
    }

    public String getName() {
    
    
        return this.targetCache.getName();
    }

    public Object getNativeCache() {
    
    
        return this.targetCache.getNativeCache();
    }

    public ValueWrapper get(Object key) {
    
    
        return this.targetCache.get(key);
    }

    public <T> T get(Object key, Class<T> type) {
    
    
        return this.targetCache.get(key, type);
    }

    public <T> T get(Object key, Callable<T> valueLoader) {
    
    
        return this.targetCache.get(key, valueLoader);
    }

    public void put(final Object key, final Object value) {
    
    
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
    
    
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    
    
                public void afterCommit() {
    
    
                    TransactionAwareCacheDecorator.this.targetCache.put(key, value);
                }
            });
        } else {
    
    
            this.targetCache.put(key, value);
        }

    }

    public ValueWrapper putIfAbsent(Object key, Object value) {
    
    
        return this.targetCache.putIfAbsent(key, value);
    }

    public void evict(final Object key) {
    
    
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
    
    
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    
    
                public void afterCommit() {
    
    
                    TransactionAwareCacheDecorator.this.targetCache.evict(key);
                }
            });
        } else {
    
    
            this.targetCache.evict(key);
        }

    }

    public void clear() {
    
    
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
    
    
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
    
    
                public void afterCommit() {
    
    
                    TransactionAwareCacheDecorator.this.targetCache.clear();
                }
            });
        } else {
    
    
            this.targetCache.clear();
        }

    }
}

Guess you like

Origin blog.csdn.net/CSDN_WYL2016/article/details/121086986