装饰者模式在源码中的应用
生活随笔
收集整理的這篇文章主要介紹了
装饰者模式在源码中的应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
裝飾器模式在源碼中也應用得非常多,在JDK 中體現最明顯的類就是IO 相關的類,如BufferedReader、InputStream、OutputStream,看一下常用的InputStream 的類結構圖:
在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 Cache getTargetCache() {return this.targetCache;} }TransactionAwareCacheDecorator 就是對Cache 的一個包裝。再來看一個MVC 中的裝飾者模式HttpHeadResponseDecorator 類
public class HttpHeadResponseDecorator extends ServerHttpResponseDecorator {public HttpHeadResponseDecorator(ServerHttpResponse delegate) {super(delegate);} }最后,看看MyBatis 中的一段處理緩存的設計org.apache.ibatis.cache.Cache 類,找到它的包定位:
從名字上來看其實更容易理解了。比如FifoCache 先入先出算法的緩存;LruCache 最近最少使用的緩存;TransactionlCache 事務相關的緩存,都是采用裝飾者模式。MyBatis源碼在我們后續的課程也會深入講解,感興趣的小伙伴可以詳細看看這塊的源碼,也可以好好學習一下MyBatis 的命名方式,今天我們還是把重點放到設計模式上。
?
總結
以上是生活随笔為你收集整理的装饰者模式在源码中的应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 装饰者模式和适配器模式对比
- 下一篇: 装饰者模式的优缺点