Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Applied Java™ Patterns - Stephen Stelting, Olav Maassen.pdf
Скачиваний:
202
Добавлен:
24.05.2014
Размер:
2.84 Mб
Скачать

How This Book Is Organized

This book is divided into two parts. Part I, “ Commonly Used Patterns,” is organized like a pattern catalogue, reference-style.

Chapter 1: “ Creational Patterns ” on page 3 discusses patterns that create objects: Abstract Factory, Builder, Factory Method, Prototype, and Singleton.

Chapter 2: “ Behavioral Patterns ” on page 39 is focused on the patterns that can determine the behavior of your object model: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, and Visitor.

Chapter 3: “ Structural Patterns ” on page 139 describes patterns that can bring structure to your application and has the following patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, HOPP, and Proxy.

Chapter 4: “ System Patterns ” on page 205 describes the patterns that help you build better architectures: Callback, Router, MVC, Session, Successive Update, Transaction, and Worker Thread.

Part II, “ Patterns in the Java Programming Language,” presents many of the Java APIs and shows the use of patterns in those API and their benefit.

Chapter 6: “ Java Core APIs ” on page 279 provides an overview in the familiar core APIs like Event Handling, JavaBeans ™, AWT and Swing, Collections, Input/Output, and Reflection.

Chapter 7: “ Distributed Technologies ” on page 303 describes selected distributed APIs and how patterns are used: JNDI, JDBC, RMI, and CORBA.

Chapter 8: “ Jini and J2EE Architectures ” on page 317 focuses on the two complementary frameworks Jini and J2EE. J2EE is further divided into Servlets, JSP and EJB technologies.

How to Use This Book

There are several ways to read this book. You could start at page one and read from cover to cover. However, we recommend you start with some of the easier patterns: Factory Method, Singleton, Observer, and Composite. Work your way through the book using those as starting points for your exploration. Alternatively, you might want to turn to sections in Part II first. Find an API you are familiar with and start looking for patterns there.

You can read the patterns in any order you feel most comfortable with. Later, you can use this book as a reference to refresh your memory when you want to put your knowledge of patterns into practice

Companion Web Site

This book has a companion Web site to provide you with updates and other material: it is located at http://www.phptr.com/appliedjavapatterns.

Acknowledgments

A book is, above all else, a team effort. We’d like to thank all the people who made this a reality. We’ve worked with an exceptionally fine group. This page is dedicated to them, to let them know that their efforts are appreciated.

For Greg Doench, Prentice Hall visionary: Thank you for being the Great Unifier for this project. When we started this work, we discovered Greg was a marathon runner. When Steve mentioned that he would like to try his hand (feet?) at the sport, Greg said, “After the book is done.” Now we understand why: writing a book is itself a marathon. For your ongoing help and support, and for your belief in this book, our most sincere thanks.

For Rachel Borden, Sun Press luminary: Thank you for your guidance along the path to publication. If not for your help, we’d still be scrawling ideas across massive expanses of sticky notes. Thank you for your ongoing support and dedication, and for having patience when explaining to techies how publishing works. Our thanks for getting up far too early on far too many mornings for conference calls with people on the other side of the world. Most of all, thanks for being a continuing champion of our work.

5

For Solveig Haugland, content editor extraordinaire: Thank you for believing in the dream, and for helping to make it a reality. Thank you for working your mambo (mojo?) and turning a jumble of unconnected ideas into something far greater—one big rambling idea, perhaps. And thank you for showing us that it is possible to put a bit of humor into a technical book, after all.

For our talented technical reviewers: Thanks for making us think hard about what we actually wanted to say. Our most sincere thanks go to Jennie Yip for spending long hours writing up every detail she could find, Bryan Basham, Bert Bates, John Crupi, Jim Gallentine, Werner van Mook, Nanno Schering, Juergen Schimbera, Robert Schrijvers and Fred Zuijdendorp.

Many thanks to the production team at Prentice Hall. We’re genuinely sorry that we didn’t get a chance to meet you, but we know that you’re out there turning ideas into reality. Yours is truly inspiring work—helping to bring dreams and ideas out into the world. For your commitment and hard work on this book, and the other books you have made (many of which have a place in our hearts and on our shelves) we thank you.

Stephen Stelting would like to thank: Steve Bradshaw, Annette Baldenegro, Cindy Lewis, and the rest of the management team of Sun Educational Services: Thank you for the support you’ve shown and for the faith you’ve had in me during this past year. I appreciate your help and understanding more than I can say.

I promise to try and get a life now.

Olav Maassen wishes to thank: Harry Pallandt and Andre Arnoldus, my managers, for letting me work late many times, and for their support over the years.

Ingrid, Niels – The two biggest stars of my universe for providing all the support, encouragement and motivation for me to finish this project.

Britt – The third star of my universe for waiting long enough to be born to allow me to finish the book first before moving on to my next big project—my family.

Why Patterns?

“If builders built houses the way programmers wrote code, the first woodpecker that came along would destroy civilization.”

If you wanted to build a house, how would you do it?

Well, you could do what some people do to build a treehouse:

Find a sturdy tree.

Get a bunch of wood, a hammer, and some nails.

Apply the products from step 2 to step 1.

Hope for the best.

Of course, anyone who has tried this approach knows the results can be disappointing—in some cases, leading to the loss of the tree along with the treehouse. A better plan would be to find an architect and get his or her help in developing blueprints.

But how does the architect, the expert in building houses, make decisions? How is it possible to take the lessons from years of experience and apply them to creating a brand new home? There’s a certain something, a base of knowledge, experience and perhaps a little intuition, that seems to make the architect successful.

The questions about building and designing houses are really not all that different from the ones we face in the software development world. How can we effectively design good software? How can we apply experience gained in the past to projects in the future? How can we make decisions during design that will produce software that has good characteristics, like flexibility, extensibility and efficiency?

As in our building project, we need experienced guidance. We need some equivalent of our building architect, someone who has a balance of knowledge, experience and good common sense in software design. We need a software development guru.

6

There aren't a lot of gurus in the world. And until cloning technology is a lot more advanced, we frequently have to fend for ourselves. In our projects, in our companies, we have to make our own software experts.

So we're back to square one. We want to design good software, but we don't know how to make the right decisions, decisions that will ultimately lead us to produce a quality product. We want to grow experienced software developers, but short of a brain transplant, we don't even know how to get the knowledge of effective design from the current generation of software experts.

What if there were a way to collect that knowledge? What if we could get experience from the gurus, and it didn't even involve painful surgery? What if we could record and summarize key concepts of software design, building a foundation for our next generation of software developers?

There is such a way—it's called design patterns.

It's well-documented that experts often solve new problems by applying solutions that have worked in the past. They identify parts of their problem that are like problems that they have encountered before. Next, they recall the solution to their earlier problems and generalize it. Finally, they adapt the general solution to the context of their current problem.

The idea behind design patterns is to develop a standardized way to represent general solutions to commonly encountered problems in software development. There are a few benefits to doing this:

Over time, we can build up catalogs of patterns. This enables newcomers to software development to more effectively benefit from experience gained over the years.

There is formal documentation about the tradeoffs involved in software design decisions; about the pluses and minuses of development choices. Standardizing patterns makes it easier for all development professionals—beginners and experts alike—to explicitly understand the implications of their decisions.

The design patterns provide a common vocabulary. This makes communicating decisions to developers easier. Rather than describing a design in detail, we can use a pattern name to explain our plans.

We can relate patterns to each other, so that a developer can easily see which patterns might belong together in a project.

Design patterns give us an effective way to share experience throughout the object-oriented programming community. Whether we've gained the knowledge in C++, Smalltalk, or the Java programming language, whether the expertise has been built up from Web projects, legacy integration or custom work, we can collect our lessons and share them with other developers. In the long run, we can improve software development across the industry.

History of the Patterns Movement

It Came From Outer Space... via U.C. Berkeley

The inspiration for design patterns in software development is usually attributed to Christopher Alexander, a professor of architecture at U.C. Berkeley. In the late ‘70s, he published several books that introduced the concept of patterns and provided a catalog of patterns for architectural design.

Alexander's work sparked interest in the object-oriented (OO) community, and within the next decade, a number of pioneers had developed patterns for software design. Kent Beck and Ward Cunningham were among the first, discussing a set of Smalltalk design patterns in a presentation at the 1987 OOPSLA conference. James Coplien was another who actively promoted the tenets of patterns, writing a book about C++ idioms, or patterns for C++ development, in the early ’90s.

OOPSLA was an excellent venue for the growing patterns community, since it offered an environment for them to share their ideas. Another important forum for the evolution of the patterns movement was the Hillside Group, established by Kent Beck and Grady Booch.

Probably the best-known contribution to the popularity of design patterns was the 1995 book Design Patterns: Elements of Reusable Object-Oriented Software. The authors—Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—are also commonly known as the “Gang of Four” or GoF. The book introduced a comprehensive pattern language, and gave C++ examples for the patterns discussed. Another important work that gave momentum to patterns was the book Pattern-Oriented Software Architecture, A System of Patterns, by Buschmann, Meunier, Rohnert, Sommerlad and Stal.

7

Since the publication of these two books, design patterns have enjoyed substantial interest in the software community. Java (“Java technology”) grew up at the same time as patterns were gaining widespread popularity, so it was inevitable that Java developers would take an interest in applying design patterns in their projects. The growing popularity of design patterns in Java has been manifested in presentations at conferences like JavaOne, as well as patterns columns in the Java trade journals.

Basic Concepts in Patterns

“Talking the Talk”

Central to the idea of patterns is the concept of standardizing the information about a common problem and its solution. One of the most useful results of Alexander's work was the development of a template for representing patterns —what is now called a form or format. The Alexandrian Form uses five topic areas to formalize the discussion of a pattern and its solution.

Fundamentally, it’s important that a pattern provide a descriptive name for the pattern and the answer to the question “What will this pattern do for you?” In addition, it should include a discussion of the problem, an explanation of how the pattern solves the problem, and an indication of the benefits, drawbacks and tradeoffs associated with the pattern’s use.

Naturally, when patterns were adopted by the OO community, variations on the Alexandrian form were developed to meet the needs of software development. Most of the forms in use today are derived from one of two forms—the Canonical or “Gang of Four” forms. This book is based on a variation of the Gang of Four form, with the following topics forming our template:

Name – A descriptive name for the pattern.

Also Known As – Alternate names, if any.

Pattern Properties – The pattern's classification. We define a pattern in terms of two major topics.

Type:

Creational patterns for object creation

Behavioral patterns that coordinate functional interaction between objects

Structural patterns that manage static, structural relationships between objects

System patterns used to manage system-level interaction

Level:

Single Class – The pattern applies to a single class

Component – The pattern involves a group of classes

Architectural – The pattern is used to coordinate the actions of systems and subsystems

Purpose – A short explanation of what the pattern involves.

Introduction – A brief description of a problem you might be facing where this pattern may be useful, using an example to illustrate.

Applicability – When and why you might want to use this design pattern.

Description – A more detailed discussion of the pattern, what it does and how it behaves.

Implementation – A discussion of what must be done to implement the pattern. If you know you want to use this pattern, this section tells you how to implement it.

Benefits and Drawbacks – The consequences of using the pattern and tradeoffs associated with use of the pattern.

8