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.

218 Part IV • Putting It All Together: Thinking in <strong>Patterns</strong><br />

Extend software<br />

capabilities without<br />

changing it<br />

<strong>Patterns</strong> are<br />

microcosms of<br />

Alexander's<br />

philosophy<br />

The Open-Closed Principle<br />

Software clearly needs to be extensible. However, making changes to<br />

software runs the risk of introducing problems. This dilemma led<br />

Bertrand Meyer to propose the open-closed principle. 1 To paraphrase<br />

this principle, the modules, methods, and classes should be open for<br />

extension, while closed for modification. 2 In other words, we must<br />

design our software so that we can extend the capabilities of our<br />

software without changing it.<br />

As contradictory as this may sound at first, you have already seen<br />

examples of it. In the Bridge pattern, for instance, it is quite possible to<br />

add new implementations (that is, to extend the software) without<br />

changing any of the existing classes.<br />

The Principle of <strong>Design</strong>ing from Context<br />

Alexander tells us to design from context, to create the big picture<br />

before designing the details in which our pieces appear. Most design<br />

patterns follow this approach, some to a greater extent than others.<br />

Of the four patterns I have described so far, the Bridge pattern is the<br />

best example of this.<br />

Refer to the Bridge pattern diagram in Chapter 9, "The Bridge Pattern,"<br />

(see Figure 9-13). When deciding how to design the Imple -<br />

mentation classes, think about their context: the way that the<br />

classes derived from the Abstraction class will use them.<br />

For example, if I were writing a system that needed to draw shapes<br />

on different types of hardware and that therefore required different<br />

implementations, I would use a Bridge pattern. The Bridge tells me<br />

that the shapes will use my implementations (that is, the drawing<br />

1. Meyer, B., Object-Oriented Software Construction, Upper Saddle River, N.J.: Prentice<br />

Hall, 1997, p. 57.<br />

2. See this book's Web site for a link to "The Open-Closed Principle," an excellent<br />

article by Robert C. Martin. Go to http://www.netobjectives.com/dpexplained.

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

Saved successfully!

Ooh no, something went wrong!