Patterns in Java, Volume 1—A Catalog of Reusable DesignPatterns Illustrated with UML, Second Edition Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UM
Trang 1Patterns in Java, Volume 1—A Catalog of Reusable Design
Patterns Illustrated with UML, Second Edition
Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 2Patterns in Java, Volume 1—A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
Trang 3Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrievalsystem or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except
as permitted under Sections 107 or 108 of the 1976 United StatesCopyright Act, without either the prior written permission of the
copy fee to the Copyright Clearance Center, 222 Rosewood Drive,Danvers, MA 01923, (978) 750-8400, fax (978) 750-4744 Requests tothe Publisher for permission should be addressed to the Legal
Publisher, or authorization through payment of the appropriate per-Department, Wiley Publishing, Inc., 10475 Crosspointe Blvd.,
Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail:
permcoordinator@wiley.com
This publication is designed to provide accurate and authoritativeinformation in regard to the subject matter covered It is sold with theunderstanding that the publisher is not engaged in professional
services If professional advice or other expert assistance is required,the services of a competent professional person should be sought
Trang 4ISBN: 0-471-22729-3
Wiley also publishes its books in a variety of electronic formats Somecontent that appears in print may not be available in electronic
questions and comments are (in alphabetical order): Nader Afshar,Derrick Ampy, Barry W Anderson, Paul E Andrighetti, Kaushik Barot,Ted Beckett, Pablo Bellver, Davide De Benedictis, Dave Busse, MikeCarlin, Max Chandler, John Clarke, Charlie Crook, Christian Cryder,Carlos Devoto, Cyrus Doomasia, Rodrigo Figueiredo, Jeff French,Brent Fry, Srinivas Ganti, Daniel L Gleneck, Satish Gupta, Barton W.Hammond, Shannon Harvey, Judy Housman, Hong Hsu, Rob
Hulsebos, Gary Janes, Brian Krahmer, Erik Bak Kristensen, RobertLaganière, Laurene O Laidlaw, Allen Lee, Roger Lee, Tim Lethbridge,Charles Magid, Kurt Matthys, Phil McGlauchlin, Barry Middlebrook,Sadiq Mohammed, Thomas Moore, Raymond Naseef, Jaime Nino,
Trang 5Rajapakse, Steven Ranieri, John Sargeant, Robert Allan Schwartz,Greg Scott, Joe Sharp, Mike Shivas, Eduardo Silva, Daniel
Stainhauser, Steve Stephens, Christian Svenstrup, Oyvind Teig, AlanThompson, Richard Tomlinson, Bruce Wallace, Dieter Wankmueller,Mark Waschkowski, Richard Williams, Joe Wissmann, Robert Wragg,Wayne Wylupski, and Hong Yan
Acknowledgments from the First Edition
I want to thank Craig Larman, my most conscientious reviewer Heconvinced me of the importance of patterns Craig also provided mewith much invaluable feedback on the use of UML and the
presentation of patterns His valuable suggestions greatly improvedthe way that I present the patterns in this book
Jack Harich was another manuscript reviewer who made many usefulsuggestions about the organization of this book He convinced me toexpand my coverage of fundamental patterns He also supplied theexample that I use for the State pattern
Brad Appleton provided me with the most voluminous and detailedcomments
The UIUC patterns group provided some insightful discussions for thepatterns in this book The participants in those discussions includedBrian Foote, Ed Peters, Dragos Malonescu, Peter Hatch, Don
Roberts, Joseph W Yoder, Ralph Johnson, John Brant, James
Overturf, Jean Pierre Briot, Eiji Nabika, Hiro Nakamura, and Ian Chai
I also want to acknowledge some of my other reviewers, in particularMicheal Wheaton and Micheal Pair
About the Author
Trang 6experience specializing in distributed systems, object-oriented design,and Java He was the architect for the first commercial business-to-business (B2B) e-commerce product for the Internet He is currentlyworking on an open source framework for gluing components andprograms into an application
as software architect, database architect, network designer and
administrator, and Sun System administrator He has been involvedwith object-oriented programming and design since 1982
Trang 7Patterns in Java, Volume 1: A
Catalog of Reusable Design Patterns
Illustrated with UML, Second Edition
by Mark Grand
Trang 9Software Patterns
Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 10Chapter 1: Introduction to Software Patterns
Trang 11those they have solved in the past With even more experience, theyrecognize that solutions to similar problems follow recurring patterns.With knowledge of these patterns, experienced programmers canrecognize a problem to which specific patterns apply and immediatelydetermine the solution without having to stop to analyze the problemfirst
When a programmer discovers a pattern, it’s just an insight In mostcases, to go from an unverbalized insight to a well-thought-out ideathat the programmer can clearly articulate is surprisingly difficult It’salso an extremely valuable step When we understand a pattern wellenough to put it into words, we are able to intelligently combine it withother patterns More important, once put into words, a pattern can beused in discussions among programmers who know the pattern Suchdiscussions allow programmers to more effectively collaborate andcombine their wisdom They can also help avoid the situation in whichprogrammers argue over different solutions to a problem but find thatthey were actually thinking of the same solution, only expressing it indifferent ways
Putting a pattern into words has an additional benefit for less
experienced programmers who have not yet discovered the pattern.Once a pattern has been put into words, more experienced
programmers can teach it to programmers who aren’t familiar with thepattern
Trang 12programmers with a common vocabulary to discuss patterns It shouldalso allow programmers who have not yet discovered a pattern tolearn about the pattern
Although this book includes a substantial breadth of patterns, you maydiscover additional patterns yourself Some patterns that you discovermay be highly specialized and of interest only to a small number ofpeople Other patterns may be of broad interest and worthy of
inclusion in a future volume of this book If you wish to communicatesuch a pattern to this book’s author, you may send an email to
Patterns and AntiPatterns are similar but fundamentally different Thepoint of a pattern is to recognize when you have the opportunity toapply a good solution to a problem The point of an AntiPattern is torecognize the nature of a bad situation and suggest solutions
Trang 13Software Patterns
Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 14Patterns are usually described using a format that includes the
following information:
A name that is commonly used for the pattern Alternativenames are given in cases where the pattern is known by morethan one name
A description of the problem that includes a concrete exampleand a solution specific to the concrete problem
Pattern Name
The heading of this section consists of the name of the pattern Mostpatterns don’t have any additional text under this heading For thosethat do, this section contains alternate names for the pattern or
information about the derivation or general nature of the pattern
Synopsis
This section contains a brief description of the pattern The synopsis
Trang 15Don’t be discouraged if you don’t recognize a pattern from its nameand synopsis Instead, carefully read through the rest of the patterndescription to understand it
Context
This section describes the problem that the pattern addresses Formost patterns, the problem is introduced in terms of a concrete
example After presenting the problem in the example, the Contextsection suggests a design solution to the problem
Forces
The Forces section summarizes the considerations that lead to thegeneral solution presented in the Solution section It may also presentreasons to not use the solution The reasons to use or not use thesolution are presented as a bulleted list:
J Reasons to use the solution are bulleted with a happy face
L Reasons to not use the solution are bulleted with a sad face
Solution
purpose solution to the problem that the pattern addresses
The Solution section is the core of the pattern It describes a general-Implementation
The Implementation section describes important considerations whenusing the solution It may also describe some common variations orsimplifications of the solution
Consequences
Trang 16bad––of using the solution Most consequences are organized intobullet points as follows:
Code Example
This section contains a code example that shows a sample
implementation for a design that uses the pattern In most cases, thisdesign is described in the Context section
Related Patterns
This section contains a list of patterns that are related to the patterndescribed
Trang 17Software Patterns
Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 18In 1987, Ward Cunningham and Kent Beck used some of Alexander’sideas to develop five patterns for user-interface design They
published a paper on the user-interface patterns at OOPSLA-87
entitled “Using Pattern Languages for Object-Oriented Programs.”
In the early 1990s, Erich Gamma, Richard Helm, John Vlissides, andRalph Johnson began work on one of the most influential computer
books of the last decade: Design Patterns Published in 1994 and
often called the “Gang of Four,” or GoF, book, it popularized the idea
of patterns and was the greatest single influence on this book
This book is a second edition Additional patterns have been addedthat were not in the first edition Many improvements suggested byreaders of the first edition have been incorporated into the patterns.Examples have been changed to reflect more recent versions of Java.Both editions of this book represent an evolution of patterns and
objects since the GoF book was published The GoF book used C++and Smalltalk for its examples This book uses Java and takes a
rather Java-centric view of most things When the GoF book waswritten, the Unified Modeling Language (UML) did not exist; now, it iswidely accepted as the preferred notation for object-oriented analysisand design, and it is the notation used in this book
Trang 19Software Patterns
Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 20This book is the first volume of a three-volume set that covers a widerrange of patterns than previously published works
This first volume focuses exclusively on design patterns that are used
at the micro-architectural level The second volume includes patternsused during user interface design, coding and testing The third
volume focuses on architectural and design patterns useful for
enterprise and distributed applications
All three volumes begin with a description of the subset of UML used
in that volume The following chapter contains an overview of thesoftware life cycle, to provide the context in which the patterns areused This chapter goes on to provide a case study that includesexamples of using patterns in that volume The remaining chaptersdescribe different sorts of patterns
There will be a Web site related to this book at
http://mgrand.home.mindspring.com The Web site will contain
synopsis of the patterns that appear in this book The Web site willalso contain the code examples in this volume
The Java examples that appear in this book are based on Java
version 1.4
Trang 21Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 22Chapter 2: Overview of UML
Trang 23The Unified Modeling Language (UML) is a notation that you can use
for object-oriented analysis and design This chapter contains a briefoverview of UML that introduces you to the subset of UML and theextensions to UML used in this book For a complete description ofUML, see www.omg.org/technology/documents/formal/uml.htm
Java programmers For example, it uses the words attribute and
variable interchangeably, with preference for the Java-specific term variable This book also uses the words operation and method
interchangeably, with preference for the Java-specific term method.
UML defines a number of different kinds of diagrams The rest of thischapter is organized into sections that describe different kinds of UMLdiagrams and the elements that appear in them
If you are experienced with object-oriented design, you will find most
of the concepts underlying the UML notation to be familiar If you findmany concepts unfamiliar, read only as much of this chapter as youfeel comfortable with When you see a UML diagram in later chaptersthat contains something that you want explained, come back to thischapter and find a diagram that contains the UML element that youwant explained
Trang 24Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 25A class diagram is a diagram that shows classes, interfaces, and their relationships The most basic element of a class diagram is a class.
Trang 27«constructor»
In a UML drawing, a word in guillemets is called a stereotype A
stereotype is used like an adjective to modify what comes after it Theconstructor stereotype indicates that the methods following it areconstructors The misc stereotype indicates that the methods
following it are regular methods Additional uses for stereotypes aredescribed later in this chapter
One last element that appears in the class in Figure 2.1 is an ellipsis( ) If an ellipsis appears in the bottom compartment of a class, itmeans that the class has additional methods that the diagram doesnot show If an ellipsis appears in the middle compartment of a class,
it means that the class has additional variables that the diagram doesnot show
Often, it is neither necessary nor helpful to show as many details of aclass as were shown in the class in Figure 2.1 As shown in Figure2.2, a class may be drawn with only two compartments: a top
compartment, which contains the class’s name, and a bottom
compartment, which shows the class’s methods A two-compartmentclass means only that its variables are not shown; it does not meanthat the class lacks variables
Figure 2.2: Two-compartment class.
The visibility indicators may be omitted from methods and variables Amethod or variable shown without a visibility indicator means thatthere is no indication of the method’s or variable’s visibility It does notimply that the method or variable is public, protected, or private
Trang 28
Figure 2.3: Simplified class diagram.
The simplest form of a class has just one compartment that containsthe class name, as shown in Figure 2.4 A one-compartment
representation of a class merely identifies the class; it provides noindication about what variables or methods the class has
Figure 2.4: One-compartment class
Interfaces are drawn in a manner similar to classes The difference isthat the name in the top compartment is preceded by an interfacestereotype Figure 2.5 is an example of an interface
Trang 29Figure 2.5: Interface.
Classes and interfaces are important elements of class diagrams.Other elements of a class diagram show relationships between
classes and interfaces Figure 2.6 is a typical class diagram
Figure 2.6: Class diagram.
The lines in Figure 2.6 indicate the relationships between the classesand an interface A solid line with a closed hollow head, such as theone in Figure 2.7, indicates the relationship of a subclass that inheritsfrom a superclass
Trang 30Figure 2.7: Subclass inherits from superclass.
The class diagram in Figure 2.6 shows the abstract class Product asthe superclass of the ConcreteProduct class You can tell that it isabstract because its name is italicized You can tell that its methodsare abstract because they, too, are italicized
A similar sort of line is used to indicate that a class implements aninterface It is a dotted or dashed line with a closed head like the one
associations With associations can appear a number of things that
provide information about the nature of an association Although thefollowing items are optional, this book consistently uses them
wherever it makes sense to do so
Trang 31there may be an association name The name of an association isalways capitalized At one end of the association name there may be
a triangle to indicate the direction in which you should read the
association
Looking at Figure 2.6, you will see that the association between theFactory and ConcreteProduct classes has the name Creates
Role Name To clarify the nature of an association, the name of the
role each class plays in the association can appear at each end of anassociation, next to the corresponding class Role names are alwayslowercase That makes them easier to distinguish from associationnames, which are always capitalized
In Figure 2.6, the CreationRequester class and the FactoryIFinterface participate in an association named Requests-Creation.The CreationRequester class participates in that association in arole called requester The FactoryIF interface participates in thatassociation in a role called creator
Multiplicity Indicator Another helpful detail of an association is how
Trang 32association A multiplicity indicator may appear at each end of an
association to provide that information A multiplicity indicator can be asimple number, like 0 or 1, or a range of numbers indicated like this:0 2
An asterisk as the high value of a range means an unlimited number
of occurrences The multiplicity indicator 1 * means at least one
instance; 0 * means any number of instances A simple * is equivalent
to 0 * Looking at the multiplicity indicators in Figure 2.6, you see thateach one of the associations in the drawing is a one-to-many
relationship
Figure 2.9 is a class diagram that shows a class with multiple
subclasses Though the drawing in Figure 2.9 is perfectly valid, UMLallows a more aesthetically pleasing way to draw a class with multiplesubclasses You can combine the arrowheads as is shown in Figure2.10 The diagram in Figure 2.10 is identical in meaning to the
Trang 33relationship where one object contains a collection of other objects is
called an aggregation A hollow diamond at the end of the association
indicates aggregation The hollow diamond appears at the end of theassociation attached to the class that contains instances of the otherclass The class diagram in Figure 2.11 shows an aggregation
Figure 2.11: Aggregation.
The class diagram in Figure 2.11 shows a class named MessageManager Each of its instances contains zero or more instances of aclass named MIMEMsg
UML has another notation to indicate a stronger relationship than
aggregation That relationship is called composite aggregation For an
aggregation to be composite, two conditions must be satisfied:
Aggregated instances must belong to only one composite at atime
Some operations must propagate from the composite to itsaggregated instances For example, when a composite object
is cloned, its clone method will typically clone the aggregatedinstances so that the cloned composite will own clones of theoriginal aggregated instances
Figure 2.12 is a class diagram that contains a composite aggregation
Trang 34Figure 2.12: Composite aggregation.
The class diagram in Figure 2.12 shows a Document class
Document objects can contain Paragraph objects; Paragraphobjects can contain DocChar objects Because of the compositeaggregation, you know that Paragraph objects do not share
DocChar objects and Document objects do not share Paragraphobjects
Some associations are indirect Instead of classes being directlyassociated with each other, they are associated indirectly through athird class Consider the class diagram in Figure 2.13
Figure 2.13: Association class.
Trang 35There is another use for ellipsis in a class diagram Some class
diagrams need to show that a class has a large or open-ended set ofsubclasses, while only showing a few subclasses as examples of thesort of subclasses that the class has The class diagram in Figure2.14 shows how ellipsis can be used to show just that
Figure 2.14: Open-ended subclasses.
The class diagram in Figure 2.14 shows a class named DataQuery.The DataQuery class has subclasses named JDBCQuery,
OracleQuery, Sybase Query, and an indefinite number of otherclasses that are indicated by the ellipsis
An association between classes or interfaces implies a dependencythat involves an object reference connecting two objects Other types
of dependencies are possible A dashed line is used to indicate adependency in the more general sense Figure 2.15 shows an
example of such a dependency
Trang 36Figure 2.15: Dependency.
The classes in a class diagram can be organized into packages Apackage is drawn as a large rectangle above which lies a small
rectangle containing the package name The small and large
rectangles are arranged to have an overall shape similar to that of amanila folder The class diagram in Figure 2.16 contains a package
Figure 2.16: Package.
Figure 2.16 shows a package named ServicePackage A visibilityindicator can precede the name of classes and interfaces that appearwithin a package Public classes are accessible to classes outside ofthe package; private classes are not
Sometimes there are aspects of a design that you cannot make
sufficiently clear without a comment in a diagram Comments in UMLare drawn as a rectangle with its upper right corner turned down.Comments are attached to the diagram element to which they relate
Trang 37a comment about it.Class diagrams can include objects Most of theobjects in the class diagrams in this book are drawn as shown in
Some diagrams indicate an object as just an empty rectangle
Trang 38of object However, they can be used in a diagram that shows a
structure in which objects of unspecified types are connected Theclass diagram in Figure 2.19 shows such a structure
Figure 2.19: Blank objects.
The lines that connect two objects are not associations but links
Whereas links are connections between objects, associations arerelationships between classes A link is an occurrence of an
association, just as an object is an instance of a class Links can haveassociation names, navigation arrows, and most of the other
embellishments that associations can have Because a link is a
connection between two objects, it may not have multiplicity indicators
or aggregation diamonds
Some diagrams consist of just objects and links Such diagrams areconsidered a kind of class diagram However, there is a special name
for this kind of diagram: object diagram Figure 2.20 is an example of
an object diagram
Figure 2.20: Object diagram.
Trang 39Patterns in Java, Volume 1: A Catalog of Reusable Design Patterns Illustrated with UML, Second Edition
by Mark Grand
John Wiley & Sons © 2002
Trang 40Class and object diagrams show relationships between classes andobjects They also provide information about interactions betweenclasses They do not show the sequence in which the interactionsoccur or any concurrency that they may have
Collaboration diagrams show objects, the links that connect them, andthe interactions that occur over each link They also show the
sequence and concurrency requirements of each interaction Figure2.21 is a simple example of a collaboration diagram
Figure 2.21: Collaboration
diagram
Any number of interactions can be associated with a link Each
interaction involves a method call Next to each interaction or group ofinteractions is an arrow that points to the object whose method iscalled by the interaction Collectively, the entire set of objects and
interactions shown in a collaboration diagram is called a collaboration.
Each interaction shown in Figure 2.21 begins with a sequence
number and a colon Sequence numbers indicate the order in whichmethod calls occur An interaction with the number 1 must come
before an interaction with the number 2, and so on
Multilevel sequence numbers consist of two or more numbers