什么时候使用装饰者模式? [英] When to Use the Decorator Pattern?
问题描述
我正在回顾我的设计模式,我在编码中尚未认真使用的一种模式是装饰器模式.
I am going over my design patterns, and one pattern I have yet to seriously use in my coding is the Decorator Pattern.
我理解这种模式,但我想知道的是现实世界中装饰者模式是最好/最优/优雅的解决方案的一些很好的具体例子.需要装饰者模式的特定情况非常方便.
I understand the pattern, but what I would love to know are some good concrete examples of times in the real world that the decorator pattern is the best/optimal/elegant solution. Specific situations where the need for the decorator pattern is really handy.
谢谢.
推荐答案
装饰器模式经常与流一起使用:您可以用流包装流以获得附加功能.我已经在 .Net 框架中看到了这一点 - 据我所知,这发生在其他地方.我最喜欢的是围绕 FileStream 使用 GZipStream,以增加压缩.
The decorator pattern is used a lot with streams: you can wrap a stream with a stream to get added functionality. I've seen this with the .Net framework - as far as I know this occurs elsewhere. My favourite is using GZipStream around a FileStream, for added compression.
这篇关于什么时候使用装饰者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!