我们什么时候需要装饰器模式

我们什么时候需要装饰器模式

本文介绍了我们什么时候需要装饰器模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候需要使用装饰器模式?如果可能,请给我一个非常适合该模式的真实示例.

When is it necessary to use the decorator pattern? If possible, give me a real world example that is well-suited for the pattern.

推荐答案

Java 中的流 - InputStreamOutputStream 的子类是装饰器模式的完美示例.

The Streams in Java - subclasses of InputStream and OutputStream are perfect examples of the decorator pattern.

例如,将文件写入磁盘:

As an example, writing a file to disk:

File toWriteTo = new File("C:\temp\tempFile.txt");
OutputStream outputStream = new FileOutputStream(toWriteTo);

outputStream.write("Sample text".getBytes());

那么您是否需要一些关于写入磁盘的额外功能:

Then should you require some extra functionality regarding the writing to disk:

File toWriteTo = new File("C:\temp\tempFile.txt");
OutputStream outputStream =
             new GZIPOutputStream(new FileOutputStream(toWriteTo));

outputStream.write("Sample text".getBytes());

通过简单地链接"构造函数,您可以创建非常强大的写入磁盘的方法.这种方式的美妙之处在于您可以稍后添加不同的(在本例中)OutputStream 实现.此外,每个实现都不知道其他实现是如何工作的——它们都只是按照同一个合同工作.这也使得单独测试每个实现变得非常容易.

By simply "chaining" the constructors, you can create quite powerful ways of writing to disk. The beauty in this way is that you can add different (in this example) OutputStream implementations later on. Also, each implementation doesn't know how the others work - they all just work to the same contract. This also makes testing each implementation very easy in isolation.

有很多可以使用装饰器模式的真实世界"示例.举个例子:


There are plenty of "real world" examples of where the decorator pattern can be used. Off the top of my head, some examples:

  • 读写磁盘(上)
  • 构建 UI 元素,例如将滚动条添加到文本区域等

Head First Design Patterns 有一些更真实"的例子.似乎 O'Reilly 有他们的示例章节,它是关于装饰模式的,是免费的;谷歌显示了这个链接:PDF

Head First Design Patterns has some more "real world" examples. It seems that O'Reilly has their sample chapter, which is on Decorator Pattern, for free; Google showed up this link: PDF

这篇关于我们什么时候需要装饰器模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 01:10