Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The Streams in Java - subclasses of <code>InputStream</code> and <code>OutputStream</code> are perfect examples of the decorator pattern.</p> <p>As an example, writing a file to disk:</p> <pre><code>File toWriteTo = new File("C:\\temp\\tempFile.txt"); OutputStream outputStream = new FileOutputStream(toWriteTo); outputStream.write("Sample text".getBytes()); </code></pre> <p>Then should you require some extra functionality regarding the writing to disk:</p> <pre><code>File toWriteTo = new File("C:\\temp\\tempFile.txt"); OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(toWriteTo)); outputStream.write("Sample text".getBytes()); </code></pre> <p>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) <code>OutputStream</code> 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.</p> <p><hr> There are plenty of "real world" examples of where the decorator pattern can be used. Off the top of my head, some examples:</p> <ul> <li>Reading and writing to disk (above)</li> <li>Construction of UI elements, such as adding scrollbars on to text areas etc</li> </ul> <p>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: <strong><a href="http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf" rel="noreferrer">PDF</a></strong> </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload