栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

前言

本文以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 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 get(Object key, Class type) {
        return this.targetCache.get(key, type);
    }

    public  T get(Object key, Callable 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();
        }

    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/389738.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号