Tải bản đầy đủ (.pdf) (839 trang)

Wiley patterns in java a catalog of reusable design patterns illustrated with UML volume 1 2nd edition sep 2002 ISBN 0471227293

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.01 MB, 839 trang )

PatternsinJava,Volume1—A
CatalogofReusableDesign
PatternsIllustratedwithUML,
SecondEdition
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


PatternsinJava,Volume1—ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
MarkGrand

WileyPublishingCompany
PublisherRobertIpsen
Editor
TheresaHudson
DevelopmentalEditor
KathrynMalin
ManagingEditor


AngelaSmith
NewMediaEditor
BrianSnapp
TextDesign&Composition
NorthMarketStreetGraphics
Designationsusedbycompaniestodistinguishtheirproductsare


oftenclaimedastrademarks.InallinstanceswhereWileyPublishing,
Inc.isawareofaclaim,theproductnamesappearininitialcapitalor
allcapitalletters.Readers,however,shouldcontacttheappropriate
companiesformorecompleteinformationregardingtrademarksand
registration.
Copyright©2002byMarkGrand.Allrightsreserved.
PublishedbyWileyPublishing,Inc.,Indianapolis,Indiana
PublishedsimultaneouslyinCanada.
Nopartofthispublicationmaybereproduced,storedinaretrieval
systemortransmittedinanyformorbyanymeans,electronic,
mechanical,photocopying,recording,scanningorotherwise,except
aspermittedunderSections107or108ofthe1976UnitedStates
CopyrightAct,withouteitherthepriorwrittenpermissionofthe
Publisher,orauthorizationthroughpaymentoftheappropriatepercopyfeetotheCopyrightClearanceCenter,222RosewoodDrive,
Danvers,MA01923,(978)750-8400,fax(978)750-4744.Requeststo
thePublisherforpermissionshouldbeaddressedtotheLegal
Department,WileyPublishing,Inc.,10475CrosspointeBlvd.,
Indianapolis,IN46256,(317)572-3447,fax(317)572-4447,E-mail:

Thispublicationisdesignedtoprovideaccurateandauthoritative
informationinregardtothesubjectmattercovered.Itissoldwiththe
understandingthatthepublisherisnotengagedinprofessional
services.Ifprofessionaladviceorotherexpertassistanceisrequired,
theservicesofacompetentprofessionalpersonshouldbesought.


LibraryofCongressCataloging-in-PublicationData:
ISBN:0-471-22729-3
Wileyalsopublishesitsbooksinavarietyofelectronicformats.Some
contentthatappearsinprintmaynotbeavailableinelectronic

versions.
FormoreinformationaboutWileyproducts,visitourwebsiteat
www.wiley.com.
PrintedintheUnitedStatesofAmerica.
10987654321

Acknowledgments
Iwouldfirstliketoacknowledgethepatienceofmywife,Nicole.
Withouthersupport,thissecondeditionofPatternsinJava,Volume1
wouldnothavebeenpossible.
IwouldalsoliketoacknowledgethefeedbackthatIhavereceived
frommanyreaderswhoseemailstomesuggestedimprovementsand
correctionsthathavegoneintothissecondedition.Iwouldliketo
singleoutEdRemmell,whoorganizedadiscussiongrouparoundmy
bookandtookthetimetosendmesummariesofthediscussions.
Otherreaderswhotookthetimeandtroubletosendmeuseful
questionsandcommentsare(inalphabeticalorder):NaderAfshar,
DerrickAmpy,BarryW.Anderson,PaulE.Andrighetti,KaushikBarot,
TedBeckett,PabloBellver,DavideDeBenedictis,DaveBusse,Mike
Carlin,MaxChandler,JohnClarke,CharlieCrook,ChristianCryder,
CarlosDevoto,CyrusDoomasia,RodrigoFigueiredo,JeffFrench,
BrentFry,SrinivasGanti,DanielL.Gleneck,SatishGupta,BartonW.
Hammond,ShannonHarvey,JudyHousman,HongHsu,Rob
Hulsebos,GaryJanes,BrianKrahmer,ErikBakKristensen,Robert
Laganière,LaureneO.Laidlaw,AllenLee,RogerLee,TimLethbridge,
CharlesMagid,KurtMatthys,PhilMcGlauchlin,BarryMiddlebrook,
SadiqMohammed,ThomasMoore,RaymondNaseef,JaimeNino,


JeffOakes,SudeshPalekar,GregPearman,JimPhipps,JohnPinto,

JonPoploskie,RajPrathinidhi,AndyPryke,TulsiRai,DamithC.
Rajapakse,StevenRanieri,JohnSargeant,RobertAllanSchwartz,
GregScott,JoeSharp,MikeShivas,EduardoSilva,Daniel
Stainhauser,SteveStephens,ChristianSvenstrup,OyvindTeig,Alan
Thompson,RichardTomlinson,BruceWallace,DieterWankmueller,
MarkWaschkowski,RichardWilliams,JoeWissmann,RobertWragg,
WayneWylupski,andHongYan.

AcknowledgmentsfromtheFirstEdition
IwanttothankCraigLarman,mymostconscientiousreviewer.He
convincedmeoftheimportanceofpatterns.Craigalsoprovidedme
withmuchinvaluablefeedbackontheuseofUMLandthe
presentationofpatterns.Hisvaluablesuggestionsgreatlyimproved
thewaythatIpresentthepatternsinthisbook.
JackHarichwasanothermanuscriptreviewerwhomademanyuseful
suggestionsabouttheorganizationofthisbook.Heconvincedmeto
expandmycoverageoffundamentalpatterns.Healsosuppliedthe
examplethatIusefortheStatepattern.
BradAppletonprovidedmewiththemostvoluminousanddetailed
comments.
TheUIUCpatternsgroupprovidedsomeinsightfuldiscussionsforthe
patternsinthisbook.Theparticipantsinthosediscussionsincluded
BrianFoote,EdPeters,DragosMalonescu,PeterHatch,Don
Roberts,JosephW.Yoder,RalphJohnson,JohnBrant,James
Overturf,JeanPierreBriot,EijiNabika,HiroNakamura,andIanChai.
Ialsowanttoacknowledgesomeofmyotherreviewers,inparticular
MichealWheatonandMichealPair.

AbouttheAuthor



MarkGrandisanAtlanta-basedconsultantwithover23yearsof
experiencespecializingindistributedsystems,object-orienteddesign,
andJava.Hewasthearchitectforthefirstcommercialbusiness-tobusiness(B2B)e-commerceproductfortheInternet.Heiscurrently
workingonanopensourceframeworkforgluingcomponentsand
programsintoanapplication.
MarkGrandismostwidelyknownforhisbest-sellingPatternsinJava
books.InadditiontoteachingJavaforSunandothertraining
organizations,Markhasbeeninvolvedinseverallarge-scale
commercialJavaprojects.
PriortohisinvolvementwithJava,Markspentover11yearsasa
designerandimplementeroffourth-generationlanguages(4GLs).His
mostrecentroleinthatveinwasasthearchitectandprojectmanager
foranelectronicdatainterchangeproduct.Markhasworkedwitha
numberofinformationtechnology(IT)organizationsincapacitiessuch
assoftwarearchitect,databasearchitect,networkdesignerand
administrator,andSunSystemadministrator.Hehasbeeninvolved
withobject-orientedprogramminganddesignsince1982.


PatternsinJava,
Volume1:A
Catalogof
ReusableDesign
Patterns
Illustratedwith
UML,Second
Edition
ISBN:0471227293
by

Mark
Grand
JohnWiley&Sons
2002(580pages)

In-depthcoverage
offorty-sevenJava
designpatterns.

TableofContents BackCover
TableofContents
PatternsinJava,Volume1—ACatalogofReusable
DesignPatternsIllustratedwithUML,SecondEdition
Chapter1 - IntroductiontoSoftwarePatterns


Chapter2 - OverviewofUML
Chapter3 - TheSoftwareLifeCycle
Chapter4 - FundamentalDesignPatterns
Chapter5 - CreationalPatterns
Chapter6 - PartitioningPatterns
Chapter7 - StructuralPatterns
Chapter8 - BehavioralPatterns
Chapter9 - ConcurrencyPatterns
OverviewofPatternsinJava,Volumes1
Appendix through3
Bibliography
Index
ListofFigures
ListofTables

ListofSidebars



Chapter1-Introductionto
SoftwarePatterns
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


Chapter1:IntroductiontoSoftwarePatterns


Overview
Softwarepatternsarereusablesolutionstorecurringproblemsthat
weencounterduringsoftwaredevelopment.Becausethisbookisall
aboutsoftwarepatterns,theyaresimplyreferredtoaspatterns
throughout.
Whatmakesabright,experiencedprogrammermuchmoreproductive
thanabright,butinexperiencedprogrammer?Experience.
Experiencegivesprogrammersawealthofwisdom.Asprogrammers
gainexperience,theyrecognizethesimilarityofnewproblemsto
thosetheyhavesolvedinthepast.Withevenmoreexperience,they
recognizethatsolutionstosimilarproblemsfollowrecurringpatterns.
Withknowledgeofthesepatterns,experiencedprogrammerscan
recognizeaproblemtowhichspecificpatternsapplyandimmediately
determinethesolutionwithouthavingtostoptoanalyzetheproblem

first.
Whenaprogrammerdiscoversapattern,it’sjustaninsight.Inmost
cases,togofromanunverbalizedinsighttoawell-thought-outidea
thattheprogrammercanclearlyarticulateissurprisinglydifficult.It’s
alsoanextremelyvaluablestep.Whenweunderstandapatternwell
enoughtoputitintowords,weareabletointelligentlycombineitwith
otherpatterns.Moreimportant,onceputintowords,apatterncanbe
usedindiscussionsamongprogrammerswhoknowthepattern.Such
discussionsallowprogrammerstomoreeffectivelycollaborateand
combinetheirwisdom.Theycanalsohelpavoidthesituationinwhich
programmersargueoverdifferentsolutionstoaproblembutfindthat
theywereactuallythinkingofthesamesolution,onlyexpressingitin
differentways.
Puttingapatternintowordshasanadditionalbenefitforless
experiencedprogrammerswhohavenotyetdiscoveredthepattern.
Onceapatternhasbeenputintowords,moreexperienced
programmerscanteachittoprogrammerswhoaren’tfamiliarwiththe
pattern.


Theintendedvalueofthisbookisthatitprovideexperienced
programmerswithacommonvocabularytodiscusspatterns.Itshould
alsoallowprogrammerswhohavenotyetdiscoveredapatternto
learnaboutthepattern.
Althoughthisbookincludesasubstantialbreadthofpatterns,youmay
discoveradditionalpatternsyourself.Somepatternsthatyoudiscover
maybehighlyspecializedandofinterestonlytoasmallnumberof
people.Otherpatternsmaybeofbroadinterestandworthyof
inclusioninafuturevolumeofthisbook.Ifyouwishtocommunicate
suchapatterntothisbook’sauthor,youmaysendanemailto


Thepatternscatalogedinthisbookconveyconstructivewaysfor
organizingpartsofthesoftwaredevelopmentcycle.Thereare,
however,nonconstructivepatternsthatcanrecurinprograms.These
arecalledAntiPatternsbecausetheycancanceloutthebenefitsof
patterns.ThisbookdoesnotattempttocatalogAntiPatterns,forthe
subjectiswellcoveredinotherbooks.
PatternsandAntiPatternsaresimilarbutfundamentallydifferent.The
pointofapatternistorecognizewhenyouhavetheopportunityto
applyagoodsolutiontoaproblem.ThepointofanAntiPatternisto
recognizethenatureofabadsituationandsuggestsolutions.


Chapter1-Introductionto
SoftwarePatterns
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


PatternsDescription
Patternsareusuallydescribedusingaformatthatincludesthe
followinginformation:
Anamethatiscommonlyusedforthepattern.Alternative
namesaregivenincaseswherethepatternisknownbymore
thanonename.
Adescriptionoftheproblemthatincludesaconcreteexample
andasolutionspecifictotheconcreteproblem.

Asummaryoftheconsiderationsthatleadtotheformulation
ofageneralsolutionortheavoidanceofthesolution.
Ageneralsolution.
Theconsequences––goodandbad––ofusingthegiven
solutiontosolveaproblem.
Alistofrelatedpatterns.
Patternbooksdifferinhowtheypresentthisinformation.Theformat
usedinthissetofbooksvarieswiththephaseofthesoftwarelife
cyclethatthepatternaddresses.Thepatternsinthisvolumeareall
relatedtothedesignphase.Thedescriptionsofdesign-phase-related
patternsinthisvolumeareorganizedintosectionswiththefollowing
headings:

PatternName
Theheadingofthissectionconsistsofthenameofthepattern.Most
patternsdon’thaveanyadditionaltextunderthisheading.Forthose
thatdo,thissectioncontainsalternatenamesforthepatternor
informationaboutthederivationorgeneralnatureofthepattern.

Synopsis
Thissectioncontainsabriefdescriptionofthepattern.Thesynopsis


conveystheessenceofthesolutionprovidedbythepattern.The
synopsisisprimarilydirectedatexperiencedprogrammerswhomay
recognizethepatternasonetheyalreadyknowbutforwhichthey
maynothavehadaname.
Don’tbediscouragedifyoudon’trecognizeapatternfromitsname
andsynopsis.Instead,carefullyreadthroughtherestofthepattern
descriptiontounderstandit.


Context
Thissectiondescribestheproblemthatthepatternaddresses.For
mostpatterns,theproblemisintroducedintermsofaconcrete
example.Afterpresentingtheproblemintheexample,theContext
sectionsuggestsadesignsolutiontotheproblem.

Forces
TheForcessectionsummarizestheconsiderationsthatleadtothe
generalsolutionpresentedintheSolutionsection.Itmayalsopresent
reasonstonotusethesolution.Thereasonstouseornotusethe
solutionarepresentedasabulletedlist:
J

Reasonstousethesolutionarebulletedwithahappyface.

L

Reasonstonotusethesolutionarebulletedwithasadface.

Solution
TheSolutionsectionisthecoreofthepattern.Itdescribesageneralpurposesolutiontotheproblemthatthepatternaddresses.

Implementation
TheImplementationsectiondescribesimportantconsiderationswhen
usingthesolution.Itmayalsodescribesomecommonvariationsor
simplificationsofthesolution.

Consequences



TheConsequencessectionexplainstheimplications––goodand
bad––ofusingthesolution.Mostconsequencesareorganizedinto
bulletpointsasfollows:
J

Goodconsequencesarebulletedwithahappyface.

l

Neutralconsequencesarebulletedwithadot.

L

Badconsequencesarebulletedwithasadface.

JavaAPIUsage
WhenthereisanappropriateexampleofthepatterninthecoreJava
API,it’spointedoutinthissection.Thosepatternsthatarenotusedin
thecoreJavaAPIdonothavethissectionintheirdescription.

CodeExample
Thissectioncontainsacodeexamplethatshowsasample
implementationforadesignthatusesthepattern.Inmostcases,this
designisdescribedintheContextsection.

RelatedPatterns
Thissectioncontainsalistofpatternsthatarerelatedtothepattern
described.



Chapter1-Introductionto
SoftwarePatterns
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


ABriefHistoryofPatterns
Theideaofsoftwarepatternsoriginallycamefromthefieldof
architecture.ChristopherAlexander,anarchitect,wrotetwo
revolutionarybooksthatdescribepatternsinbuildingarchitectureand
urbanplanning:APatternLanguage:Towns,Buildings,Construction
(OxfordUniversityPress,1977)andTheTimelessWayofBuilding
(OxfordUniversityPress,1979).Theideaspresentedinthosebooks
areapplicabletoanumberoffieldsoutsideofarchitecture,including
softwaredevelopment.
In1987,WardCunninghamandKentBeckusedsomeofAlexander’s
ideastodevelopfivepatternsforuser-interfacedesign.They
publishedapaperontheuser-interfacepatternsatOOPSLA-87
entitled“UsingPatternLanguagesforObject-OrientedPrograms.”
Intheearly1990s,ErichGamma,RichardHelm,JohnVlissides,and
RalphJohnsonbeganworkononeofthemostinfluentialcomputer
booksofthelastdecade:DesignPatterns.Publishedin1994and
oftencalledthe“GangofFour,”orGoF,book,itpopularizedtheidea
ofpatternsandwasthegreatestsingleinfluenceonthisbook.
Thisbookisasecondedition.Additionalpatternshavebeenadded
thatwerenotinthefirstedition.Manyimprovementssuggestedby

readersofthefirsteditionhavebeenincorporatedintothepatterns.
ExampleshavebeenchangedtoreflectmorerecentversionsofJava.
Botheditionsofthisbookrepresentanevolutionofpatternsand
objectssincetheGoFbookwaspublished.TheGoFbookusedC++
andSmalltalkforitsexamples.ThisbookusesJavaandtakesa
ratherJava-centricviewofmostthings.WhentheGoFbookwas
written,theUnifiedModelingLanguage(UML)didnotexist;now,itis
widelyacceptedasthepreferrednotationforobject-orientedanalysis
anddesign,anditisthenotationusedinthisbook.


Chapter1-Introductionto
SoftwarePatterns
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


OrganizationofThisBook
Thisbookisthefirstvolumeofathree-volumesetthatcoversawider
rangeofpatternsthanpreviouslypublishedworks.
Thisfirstvolumefocusesexclusivelyondesignpatternsthatareused
atthemicro-architecturallevel.Thesecondvolumeincludespatterns
usedduringuserinterfacedesign,codingandtesting.Thethird
volumefocusesonarchitecturalanddesignpatternsusefulfor
enterpriseanddistributedapplications.
AllthreevolumesbeginwithadescriptionofthesubsetofUMLused
inthatvolume.Thefollowingchaptercontainsanoverviewofthe

softwarelifecycle,toprovidethecontextinwhichthepatternsare
used.Thischaptergoesontoprovideacasestudythatincludes
examplesofusingpatternsinthatvolume.Theremainingchapters
describedifferentsortsofpatterns.
TherewillbeaWebsiterelatedtothisbookat
.TheWebsitewillcontain
synopsisofthepatternsthatappearinthisbook.TheWebsitewill
alsocontainthecodeexamplesinthisvolume.
TheJavaexamplesthatappearinthisbookarebasedonJava
version1.4.


Chapter2-OverviewofUML
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002


Chapter2:OverviewofUML


Overview
TheUnifiedModelingLanguage(UML)isanotationthatyoucanuse
forobject-orientedanalysisanddesign.Thischaptercontainsabrief
overviewofUMLthatintroducesyoutothesubsetofUMLandthe
extensionstoUMLusedinthisbook.Foracompletedescriptionof
UML,seewww.omg.org/technology/documents/formal/uml.htm.
BooksthatarespecificallyaboutUMLcallthepiecesofinformation

storedininstancesofaclassattributes;theycallaclass’s
encapsulationsofbehavioroperations.Thoseterms,aswithUML,are
notspecifictoanyimplementationlanguage.Thisbookisnot
languageneutral;itassumesthatyouuseJavaasyour
implementationlanguage.ItalsousesJava-specifictermsinmost
placesratherthantermsthatarelanguageneutralbutlessfamiliarto
Javaprogrammers.Forexample,itusesthewordsattributeand
variableinterchangeably,withpreferencefortheJava-specificterm
variable.Thisbookalsousesthewordsoperationandmethod
interchangeably,withpreferencefortheJava-specifictermmethod.
UMLdefinesanumberofdifferentkindsofdiagrams.Therestofthis
chapterisorganizedintosectionsthatdescribedifferentkindsofUML
diagramsandtheelementsthatappearinthem.
Ifyouareexperiencedwithobject-orienteddesign,youwillfindmost
oftheconceptsunderlyingtheUMLnotationtobefamiliar.Ifyoufind
manyconceptsunfamiliar,readonlyasmuchofthischapterasyou
feelcomfortablewith.WhenyouseeaUMLdiagraminlaterchapters
thatcontainssomethingthatyouwantexplained,comebacktothis
chapterandfindadiagramthatcontainstheUMLelementthatyou
wantexplained.


Chapter2-OverviewofUML
PatternsinJava,Volume1:ACatalogof
ReusableDesignPatternsIllustratedwith
UML,SecondEdition
byMarkGrand
JohnWiley&Sons©2002



ClassDiagram
Aclassdiagramisadiagramthatshowsclasses,interfaces,andtheir
relationships.Themostbasicelementofaclassdiagramisaclass.
Figure2.1providesanexampleofaclass,showingmanyofthe
featuresthataclasscanhavewithinaclassdiagram.

Figure2.1:Basicclass
diagram
Classesaredrawnasrectangles.Therectanglescanbedividedinto
twoorthreecompartments.TheclassrectangleshowninFigure2.1
hasthreecompartments:thetopcompartmentcontainsthenameof
theclass;themiddlecompartmentliststheclass’svariables;andthe
bottomcompartmentliststheclass’smethods.
Thesymbolsthatprecedeeachvariableandmethodarecalled
visibilityindicators.Thepossiblevisibilityindicatorsandtheir
meaningsareshowninTable2.1
Table2.1:VisibilityIndicators
VisibilityIndicators

Meaning

+

Public

#

Protected



×