裝飾器模式(Decorator)

裝飾器模式(Decorator Pattern)允許向一個(gè)現(xiàn)有的對(duì)象添加新的功能,同時(shí)又不改變其結(jié)構(gòu)。這種類(lèi)型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類(lèi)的一個(gè)包裝。這種模式創(chuàng)建了一個(gè)裝飾類(lèi),用來(lái)包裝原有的類(lèi),并在保持類(lèi)方法簽名完整性的前提下,提供了額外的功能。使用場(chǎng)景: 1、擴(kuò)展一個(gè)類(lèi)的功能。 2、動(dòng)態(tài)增加功能,動(dòng)態(tài)撤銷(xiāo)。

下面是自己寫(xiě)的測(cè)試demo,非常方便的對(duì)原先的CircleShape類(lèi)進(jìn)行了增強(qiáng),同時(shí)又不改變其結(jié)構(gòu)。

public class Main {
    public static void main(String[] args) {
        Shape shape = new CircleShape();
        shape = new RedShapeDecorator(shape);
        shape = new BlueShapeDecorator(shape);
        shape.draw();
    }

    public interface Shape {
        void draw();
    }

    public static class CircleShape implements Shape {

        @Override
        public void draw() {
            System.out.println("CircleShape drawing");
        }
    }

    public static abstract class ShapeDecorator implements Shape {
        protected Shape delegate;

        public ShapeDecorator(Shape delegate) {
            this.delegate = delegate;
        }

        @Override
        public void draw() {
            this.delegate.draw();
        }
    }

    public static class RedShapeDecorator extends ShapeDecorator {
        public RedShapeDecorator(Shape shape) {
            super(shape);
        }

        @Override
        public void draw() {
            this.delegate.draw();
            this.setRedBorder(this.delegate);
        }

        private void setRedBorder(Shape decoratedShape) {
            System.out.println("Border Color: Red");
        }
    }

    public static class BlueShapeDecorator extends ShapeDecorator {
        public BlueShapeDecorator(Shape shape) {
            super(shape);
        }

        @Override
        public void draw() {
            this.delegate.draw();
            this.setBlueBorder(this.delegate);
        }

        private void setBlueBorder(Shape decoratedShape) {
            System.out.println("Border Color: Blue");
        }
    }
}

輸出結(jié)果為

CircleShape drawing
Border Color: Red
Border Color: Blue

閱讀mybatis3源代碼的時(shí)候,其對(duì)緩存的處理就使用了裝飾器模式,通過(guò)對(duì)各種模式的緩存進(jìn)行組合,組裝出了非常強(qiáng)大的緩存處理功能,比如使用LoggingCache統(tǒng)計(jì)緩存的命中率,SynchronizedCache保證線(xiàn)程的安全性

 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);
    }
  }

public class LoggingCache implements Cache {

  private final Log log;
  private final Cache delegate;
  protected int requests = 0;
  protected int hits = 0;

  public LoggingCache(Cache delegate) {
    this.delegate = delegate;
    this.log = LogFactory.getLog(getId());
  }

  @Override
  public String getId() {
    return delegate.getId();
  }

  @Override
  public int getSize() {
    return delegate.getSize();
  }

  @Override
  public void putObject(Object key, Object object) {
    delegate.putObject(key, object);
  }

  @Override
  public Object getObject(Object key) {
    requests++;
    final Object value = delegate.getObject(key);
    if (value != null) {
      hits++;
    }
    if (log.isDebugEnabled()) {
      log.debug("Cache Hit Ratio [" + getId() + "]: " + getHitRatio());
    }
    return value;
  }

  @Override
  public Object removeObject(Object key) {
    return delegate.removeObject(key);
  }

  @Override
  public void clear() {
    delegate.clear();
  }

  @Override
  public int hashCode() {
    return delegate.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    return delegate.equals(obj);
  }

  private double getHitRatio() {
    return (double) hits / (double) requests;
  }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容