23.07.2012 Views

Design Patterns Explained

Design Patterns Explained

Design Patterns Explained

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

248 Part V • Handling Variations with <strong>Design</strong> <strong>Patterns</strong><br />

This creates a Headerl object trailed by a Header2 object trailed by a<br />

Footerl object trailed by a SalesTicket object.<br />

Decomposing by The Decorator pattern helps to decompose the problem into two<br />

responsibilities parts:<br />

Stream I/O<br />

• How to implement the objects that give the new functionality<br />

• How to organize the objects for each special case<br />

This allows me to separate implementing the Decorators from the<br />

object that determines how they are used. This increases cohesion<br />

because each of the Decorators is only concerned with the func tion<br />

it adds— not in how it is added to the chain.<br />

Another Example: Input/Output<br />

A common use for the Decorator pattern is in stream I/O. Let's look at<br />

stream I/O a little before seeing how the pattern can be used here.<br />

I will limit the discussion to input since output works in an<br />

analogous way (if you see how it works in one direction, it should be<br />

clear how it works in the other direction). For any particular stream<br />

input, there is exactly one source, but there can be any number<br />

(including zero) of actions to perform on the input stream. For<br />

example, I can read from<br />

• A file<br />

• A socket and then decrypt the incoming stream<br />

• A file and then decompress the incoming data<br />

• A string<br />

• A file, decompress the input, and then decrypt it<br />

Depending upon how the data were sent (or stored) any combination<br />

of behaviors is possible. Think of it this way: Any source can be

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!