Another Example: Input/Output

A common use for the Decorator pattern is in stream I/O. Let's look at stream I/O a little before seeing how the pattern can be used here. I will limit the discussion to input since output works in an analogous way (if you see how it works in one direction, it should be clear how it works in the other direction). For any particular stream input, there is exactly one source, but there can be any number (including zero) of actions to perform on the input stream. For example, I can read from

  • A file

  • A socket and then decrypt the incoming stream

  • A file and then decompress the incoming data

  • A string

  • A file, decompress the input, and then decrypt it

Depending upon how the data were sent (or stored) any combination of behaviors ...

Get Design Patterns Explained: A New Perspective on Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.