我们什么时候需要装饰图案? [英] When do we need decorator pattern?

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

问题描述

何时需要使用装饰图案?如果可能的话,给我一个非常适合这种模式的真实世界的例子。

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中的Streams - InputStream OutputStream 是装饰器模式的完美示例。

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元素,如在文本区域上添加滚动条等。

头部设计模式有一些更真实世界的例子。看来O'Reilly有他们的样本章节,这是在Decorator Pattern上免费的; Google显示了此链接: 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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆