23.07.2012 Views

Design Patterns Explained

Design Patterns Explained

Design Patterns Explained

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15 • The Decorator Pattern 243<br />

In this solution, I have put the control in SalesTicket, with flags<br />

saying whether it is to print the headers or the footers.<br />

This works quite well if I do not have to deal with a lot of options or if<br />

the sales orders using these headers do not change.<br />

If I have to deal with many different types of headers and footers,<br />

printing only one each time, then I might consider using one Strategy<br />

pattern for the header and another Strategy pattern for the footer.<br />

What happens if I have to print more than one header and/or footer<br />

at a time? Or what if the order of the headers and/or footers needs to<br />

change? The number of combinations can quickly overwhelm.<br />

In situations like this, the Decorator pattern can be very useful.<br />

Instead of controlling added functionality by having a control<br />

method, the Decorator pattern says to control it by chaining<br />

together the functions desired in the correct order needed. The Decorator<br />

pattern separates the dynamic building of this chain of functionality<br />

from the client that uses it, in this case, the SalesOrder.<br />

The Decorator Pattern<br />

According to Gang of Four, the Decorator pattern's intent is to<br />

Attach additional responsibilities to an object dynamically.<br />

Decorators provide a flexible alternative to subclassing<br />

for extending functionality. 1<br />

The Decorator pattern works by allowing me to create a chain of<br />

objects that starts with the decorator objects— the objects responsible<br />

for the new function— and ends with the original object. Figure 15-3<br />

illustrates this.<br />

1. Gamma, E., Helm, R., Johnson, R., Vlissides, J., <strong>Design</strong> <strong>Patterns</strong>: Elements of Reusable<br />

Object-Oriented Software, Reading, Mass.: Addison-Wesley, 1995, p. 315.<br />

The approach is not<br />

flexible<br />

The Decorator<br />

pattern helps<br />

The intent, according<br />

to the Gang of<br />

Four<br />

How it works

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

Saved successfully!

Ooh no, something went wrong!