SKIP THE SHIPPING
Use code NOSHIP during checkout to save 40% on eligible eBooks, now through January 5. Shop now.
Register your product to gain access to bonus material or receive a coupon.
Praise for Design Patterns Java™ Workbook
“An excellent book... I’m incredibly impressed with how readable it is. I understood every single chapter, and I think any reader with any Java familiarity would. This book is going to be required reading in a lot of places, including my office.”
—Joshua Engel“Provides a new, more Java-literate way to understand the 23 GoF patterns.”
—Bob Hanmer“This book translates Design Patterns into what Java programmers need to know. It is full of short, engaging programming and design problems with solutions—making it easy for programmers to work through solutions and really make patterns ‘stick.’”
—Rebecca Wirfs-Brock“This is one exciting book. It’s approachable, readable, interesting, instructive, and just plain valuable. It’ll eclipse all other books purporting to teach people the GoF patterns in Java—and perhaps any other language.”
—John VlissidesJava programmers, you now have the resource you need to harness the considerable power of design patterns. This unique book presents examples, exercises, and challenges that will help you apply design pattern theory to real-world problems. Steve Metsker's learn-by-doing approach helps you enhance your practical skills and build the confidence you need to use design patterns effectively in mission-critical applications.
Design Patterns Java™ Workbook features the twenty-three foundational design patterns introduced in the classic book Design Patterns (Addison-Wesley, 1995). In this new, hands-on workbook, the patterns are organized into five major categories: interfaces, responsibility, construction, operations, and extensions. Each category begins with a chapter that reviews and challenges your ability to apply facilities built into Java. These introductory sections are followed by chapters that explain a particular pattern in detail, demonstrate the pattern in use with UML diagrams and Java code, and provide programming problems for you to solve.
With this book you will build expertise in important areas such as:
Solutions to the design pattern challenges appear in the back of the book, so you can compare your own work to expert approaches. A brief guide to UML explains the modeling notation, and an accompanying Web site provides all the code examples from the book.
Through the instruction and exercises offered in Design Patterns Java™ Workbook, you can fully understand the role of design patterns in Java application development, and enhance your ability to put design patterns to work.
Introduction to Design Patterns
Using Abstractions and the Bridge Pattern in Java
Using the STATE Design Pattern in Java
Click below for Sample Chapter(s) related to this title:
Sample Chapter
Foreword.
Preface.
1. Introduction to Patterns.
Why Patterns?
Why Design Patterns?
Why Java?
Why UML?
Why a Workbook?
The Organization of This Book.
Welcome to Oozinoz!
Source Code Disclaimer.
Summary.
I. NTERFACE PATTERNS.
2. Introducing Interfaces.Ordinary Interfaces.
Interfaces and Obligations.
Placing Constants in Interfaces.
Summary.
Beyond Ordinary Interfaces.
3. Adapter.Adapting in the Presence of Foresight.
Class and Object Adapters.
Unforeseen Adaptation.
Recognizing ADAPTER.
Summary.
4. FAÇADE.Refactoring to FAÇADE.
Facades, Utilities, and Demos.
Summary.
5. Composite.An Ordinary Composite.
Recursive Behavior in Composites.
Trees in Graph Theory.
Composites with Cycles.
Consequences of Cycles.
Summary.
6. Bridge.A Classic Example of BRIDGE: Drivers.
Refactoring to BRIDGE.
A Bridge Using the List Interface.
Summary.
II. Responsibility Patterns.
7. Introducing Responsibility.Ordinary Responsibility.
Controlling Responsibility with Visibility.
Summary.
Beyond Ordinary Responsibility.
8. SINGLETON.SINGLETON Mechanics.
Singletons and Threads.
Recognizing SINGLETON.
Summary.
9. OBSERVER.A Classic Example: OBSERVER in Swing.
Model/View/Controller.
Maintaining an Observable Object.
Summary.
10. MEDIATOR.A Classic Example: GUI Mediators.
Relational Integrity Mediators.
Summary.
11. Proxy.A Classic Example: Image Proxies.
Image Proxies Reconsidered.
Remote Proxies.
Summary.
12. Chain of Responsibility.Varieties of Lookup.
Refactoring to CHAIN OF RESPONSIBILITY.
Anchoring a Chain.
CHAIN OF RESPONSIBILITY without COMPOSITE.
Summary.
13. FLYWEIGHT.Recognizing FLYWEIGHT.
Immutability.
Extracting the Immutable Part of a Flyweight.
Sharing Flyweights.
Summary.
III. CONSTRUCTION PATTERNS.
14. Introducing Construction.Ordinary Construction.
Superclass Collaboration.
Collaboration within a Class.
Summary.
Beyond Ordinary Construction.
15. Builder.Building from a Parser.
Building under Constraints.
Building a Counteroffer.
Summary.
16. FACTORY METHOD.Recognizing FACTORY METHOD.
A Classic Example of FACTORY METHOD: Iterators.
Taking Control of Which Class to Instantiate.
FACTORY METHOD in Parallel Hierarchies.
Summary.
17. Abstract Factory.Abstract Factories for Families of Objects.
Packages and Abstract Factories.
Abstract Factories for Look-and-Feel.
Summary.
18. Prototype.Prototypes as Factories.
Prototyping with Clones.
Using Object.clone().
Summary.
19. Memento.Memento Durability.
Applying Memento.
Persisting Mementos across Sessions.
Using Strings as Mementos.
Summary.
IV. OPERATION PATTERNS.
20. Introducing Operations.Operations, Methods, and Algorithms.
The Mechanics of Methods.
Exceptions in Methods.
Summary.
Beyond Ordinary Operators.
21. TEMPLATE METHOD.A Classic Example of TEMPLATE METHOD: Sorting.
Completing an Algorithm.
TEMPLATE METHOD Hooks.
Refactoring to TEMPLATE METHOD.
Summary.
22. STATE.Modeling States.
Refactoring to STATE.
Making States Constant.
Summary.
23. STRATEGY.Modeling Strategies.
Refactoring to STRATEGY.
Comparing STRATEGY and STATE.
Comparing STRATEGY and TEMPLATE METHOD.
Summary.
24. Command.A Classic Example: Menu Commands.
Using COMMAND to Supply a Service.
COMMAND in Relation to Other Patterns.
Summary.
25. INTERPRETER.An INTERPRETER Example.
Interpreters, Languages, and Parsers.
Summary.
V. EXTENSION PATTERNS.
26. Introducing Extensions.Reuse as an Alternative to Extension.
Extending by Subclassing.
The Liskov Substitution Principle.
Extending by Delegating.
Summary.
Beyond Ordinary Extension.
27. DECORATOR.A Classic Example of DECORATOR: Streams.
Function Decorators.
Decorating without DECORATOR.
Summary.
28. Iterator.Type-Safe Collections.
Iterating Over a Composite.
Thread-Safe Iterators.
Summary.
29. VISITOR.Supporting VISITOR.
Extending with VISITOR.
VISITOR Cycles.
VISITOR Controversy.
Summary.
VI. APPENDIXES.
Appendix A: Directions.At OOPSLA 2000 in Minneapolis, Minnesota, I asked Mike Hendrickson of Addison-Wesley what types of books he thought readers wanted. I was interested to hear that he felt that there is still a market for books to help readers understand design patterns. I suggested the idea of a Java workbook that would give readers a chance to expand and to exercise their understanding of patterns. This sounded good to Mike, and he introduced me to Paul Becker, who supports Addison-Wesley's Software Patterns series. Paul's immediate response was that such a book "should have been written five years ago." I would like to thank Mike and Paul for their initial encouragement, which inspired me to take on this task.
Since that initial meeting, Paul has supported me throughout the entire development process, guiding this book toward publication. Early on, Paul asked John Vlissides, the Software Patterns series editor, for his views on the project. John's reply was that Paul should support the project "in all wise," inspirational words that have stayed with me throughout.
John Vlissides is also, of course, one of the four authors of Design Patterns. John and his coauthors--Erich Gamma, Ralph Johnson, and Richard Helm--produced the work that is in every way the foundation of this book. I referred to Design Patterns nearly every day that I worked on this book and can hardly overstate my reliance on it.
I have also relied on many other existing books, which are listed in the bibliography at the end of this book. In particular, I have depended on The Unified Modeling Language User Guide (Booch, Rumbaugh, and Jacobson 1999) for its clear explanations of UML. For accuracy in Java-related topics I have consulted Java™ in a Nutshell (Flanagan 1999b) almost daily. I have also repeatedly drawn on the insights in Patterns in Java™ (Grand 1998) and Java™ Design Patterns (Cooper 2000).
During the months that I was working on this book, I also worked at a financial services institution that has facilities in many locations. As the book emerged, I developed an instructor's course to go with it. I taught the course in Richmond, Virginia, and my associates Tim Snyder and Bill Trudell taught the course concurrently at other locations. I would like to thank these instructors and the students from all three courses for their inspiration and their many insights. In particular, I would like to thank Srinivasarao Katepalli, Brad Hughes, Thiaga Manian, Randy Fields, Macon Pegram, Joe Paulchell, Ron DiFrango, Ritch Linklater, Patti Richards, and Ben Lewis for their help and suggestions. I would also like to thank my friends Bill Wake and Gagan Kanjlia for their reviews of this book in its early stages and Kiran Raghunathan for his help in the later stages. Finally, I'd like to thank my friend Jeff Damukaitis for his suggestions, particularly his insistence that I make the code for this book available to readers. (It is, at oozinoz.com).
As the book came along, Paul Becker arranged for many excellent reviewers to help guide its progress. I'd like to thank John Vlissides again for his reviews. In every review, John somehow convinced me that he liked the book while simultaneously pointing out scores of significant improvements. I'd like to thank Luke Hohmann, Bob Hanmer, Robert Martin, and Joshua Kerievsky for their help at various stages. Each of them made this book better. I'd like to thank Joshua Engel, who has an amazing ability to blend sharp insight with a gentle touch. Finally, I'd like to thank Rebecca Wirfs-Brock, who had many great suggestions, including completely reorganizing the book. I had initially not taken care to put important but understandable patterns up front. The book is much stronger now because of Rebecca's advice and the help of all the book's reviewers.
Steve Metsker (Steve.Metsker@acm.org)
Symbols#, +, -, meaning in UML, 443
Underscores in class names, 17AAbstract classes
Component class as, 51
contrasted with interfaces, 14-15, 359
defined, 449
in Design Patterns, 13
refactoring into bridge classes, 70-73
role in abstractions, 65
subclassing, 26
ABSTRACT FACTORY, 175-182
families of objects and, 175-179
function of, 156
look-and-feel and, 180-182
object type unknown in, 422
overview of, 175
packages and, 179-180
summary of, 182
Abstract methods
concrete methods dependence on, 70-71
defined, 449
Abstract syntax trees, 350, 449
Abstractions
defined, 449
drivers as example of, 65
implementing, 65
JDBC driver example, 67-68
AbstractTableModel class, 27-28, 364
accept( ) method, 338-339, 343, 436
ActionListener interface, 252, 420
actionPerformed( ) method
BinStack object and, 278
overriding, 252, 420-421
polymorphism and, 249-250
active object
in an example, 129
UML, 446
ADAPTER, 21-35
class and object adapters, 26-31
driver instances of, 65
foreseen adaptation, 21-25
recognizing, 33-34, 366
summary of, 34-35
unforeseen adaptation, 31-33
Advisor interface, 242
Aerial shells
construction of, 171
cyclic composites and, 319
defined, 449
manufacturing model for, 59-63
overview of, 1-2
RocketSim example, 22
Alexander, Christopher, 1
Algorithms
compared with strategies, 237
defined, 206-207, 449
implementing in a method, 215
sorting and, 215-216
TEMPLATE METHOD and, 218-221
Analyses. See Assays
Anchoring a chain of responsibility, 135-136
API (application programming interface)
defined, 449
INTERPRETER and, 260
JDBC as, 66
Apogee
apogee( ) method, 15
defined, 449
getApogee( ) method, 128, 386
Application programming interface. See API
Arithmetic class, 305-306
ArrayList
clone( ) method and, 334
type-safe collections and, 314-315, 317
Arrays, representation of, 283
Arrays.asList( ) method, 167, 282-283, 427
Assays
defined, 450
graph theory and, 55
Aster star press, 218-221, 254-255, 413BBallisticsLabel class, 96, 379-380
BallisticsPanel_1, 90, 95
Behaviors
adding to collections, 287
composing vs. altering in DECORATOR, 432
composing with
DECORATOR, 289
inheriting from existing collections, 317-318
recursive, in COMPOSITE, 52-54
biggie object, RocketImpl class, 127, 386
Bin stacking application, 274-275
BinStack class, 276-277, 424-425
Body, method declaration and, 209
Boolean subclasses, 265
BorderFactory class, 166-167, 390, 398-399
Borders, setting with Java Swing, 308-309
BRIDGE, 65-74
drivers as example of, 65-69
list interface of, 73-74
overview of, 65
refactoring, 70-73
summary of, 74
Brightness, of objects, 306-307, 431-432
BufferedReader class, 294-295
BUILDER, 157-163
building counteroffers, 161-162
building from a parser, 157-159
building under constraints, 159-161
overview of, 156-157
summary of, 163
Building Parsers with JavaTM (Metsker), 270
Burn rate, rockets, 90
Business objects
defined, 450
separating from GUI objects, 94, 98
Buttons, rollover effect and, 309
Byte streams, 292CC++, 13
Carousel door, state of, 226-229
Carousels, defined, 450
CHAIN OF RESPONSIBILITY, 131-137
anchoring chains, 135-136
implementing operations, 206, 411
lookups and, 131-132
overview of, 131
refactoring to, 132-135
summary of, 137
without composites, 136-137
Challenges, value of, 355
ChangeListener, 379
Character streams, 292
Checked exceptions, 212, 412
CheckFactoryCanada class, 178, 403
Chemical_1 class, 143, 391, 392
ChemicalFactory_1 class, 143-147, 392
ChemicalImpl class, 147, 392-393
The Chemistry of Fireworks (Russell), 23
Circles, plotting, 302-303
Class adapters
ADAPTER and, 26-31
JTable example, 34
Class constructors, 151
Class diagrams
defined, 450
showing relationship between drivers and applications, 67
slider events and, 93
UML, 441-446
Class/instance paradigm, Java, 5
Class instantiation, 169-171
Class libraries,
multithreaded environments and, 85
Class path, searching for files along, 239-240, 291-292
Class relationships, UML, 444-445
Classes
defining qualities of, 78-79, 375
extending by subclassing, 279-281
getClass( ) method, 274
interfaces and
implementation, 13
private visibility of, 84, 376
UML, 442-443
Classic design patterns, 356
Classification constants, 17-19, 153-154
ClassificationConstants interface, 19, 362
Clients, one-to-many dependencies and, 89
clone( ) methods
limitations for copying objects, 185
Object class and, 274
OzTextArea.clone( ) and, 187
shallow copy with, 334
use as object factory, 398
Clones, prototyping with, 185-188
Code
applying design patterns to, 356-357
downloading from www.oozinoz.com, 355
enforcing consistency of, 279-280, 426-427
extending by delegation, 283-285
extending by subclassing, 279-281
layering, 94-95
Oozinoz source code, 9
refactoring, 17-18, 224
reusing as alternative to extending, 273-279
writing for composite iterator, 324
Collaboration
within classes, 153-154
superclass collaboration, 152-153
Collections
adding behaviors to, 287
cloning, 334
iterating behavior from existing, 317-318
thread safety of, 330
Collections class
INTERPRETER and, 259
java.util package, 216
synchronizedList( ) method, 330
type-safe collections, 317
Collections.sort( ) method, 247, 419-420
Command classes, 263
COMMAND, 249-271
executing op