0% found this document useful (0 votes)
203 views

Allen Holub's UML Reference Card

This reference covers the notation described in the OMG UML version 2. Bear in mind that UML is just a notation that's used in the context of a good OODesign process. Unless we teach people how to design, the languages matter very little.

Uploaded by

eBeliBala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Allen Holub's UML Reference Card

This reference covers the notation described in the OMG UML version 2. Bear in mind that UML is just a notation that's used in the context of a good OODesign process. Unless we teach people how to design, the languages matter very little.

Uploaded by

eBeliBala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

11/26/12

Allen Holub's UML Reference Card

"Wecanwritegoodorbadprogramswithanytool.Unlessweteachpeople howtodesign,thelanguagesmatterverylittle."

DavidParnas

Services

Publications

Goodies

Newsletter

Company

Contact

Search

Home

AllenHolub'sUMLQuickReference
Version2.1.4(2011/09/26) http://www.holub.com/goodies/uml/ 2011,AllenI.Holub.Allrightsreserved. Youmaylinktothispage,butpleasedonot"mirror" it(makealocalcopy).Irevisethisreference periodically,andlocalcopieswillbecomeobsolete. Thisdocumentmaybereproducedanddistributed freely,providedthattheentiredocumentis distributedwithoutmodification(includingthe copyrightnotice,myurl,andthisparagraph). Thisreferencecoversthenotationdescribedinthe OMGUMLversion2.0Superstructuredocument foundathttp://www.omg.org/cgibin/doc? ptc/20030802YoucanalsofindotherUML informationontheOMGUMLsite: http://www.uml.org. Finally,bearinmindthatUMLisjustanotation that'susedinthecontextofagoodOODesign process.There'snotmuchbenefitinusingUML unlessyou'reactuallydoingOO,andmanypeople whothinktheyare,aren't.FindanOODesign readinglistat http://www.holub.com/goodies/books.html.

UMLTrainingbyAllenHolub
ThebestinhouseObjectOrientedDesignand Javatrainingavailable.
www.holub.com

AdsbyGoogle

UML

UMLUseCase Reference

UMLforJava TrainingbyAllenHolub

Miscellany
Comments.Anykindofinformationthatisn'teasilyrepresentableinUML,including comments,implementationlevelcode,etc.Alsousedforalongconstraint.Thissymbolis usedinalloftheUMLdiagrams.

www.holub.com/goodies/uml/

1/22

11/26/12

Allen Holub's UML Reference Card

OrganizationalDiagrams
Packages Grouptogetherfunctionallysimilarclasses. SameasC++namespace. identifiesderivation.Classes/interfacesin"base"packageare extended/implementedin"derived"package,etc.Derivedclasses neednotbeinthesamepackageasbaseclass,however. representsadependency,typicallystereotyped(import, access,etc.). Packagenameispartoftheclassname.(e.g.giventheclassfredin theflintstonepackage,thefullyqualifiedclassnameis flintstone.fred). Generallyneededwhenentirestaticmodelwon'tfitononesheet. Packagescannest.Outermostpackagescalleddomainsifthey containonlysubpackages(noclasses).(Thetoolspackageatleftis anouterpackagethecom.holub packageisadomain.)Nested packagescanalsobeshownusinga treestructureandstaticmodelnested classsymbol(shownatright). Subsystems.Asubsystemisacooperatingsetofruntimeobjectsthatform acohesivegroup.(Packagesaremadeupofclasses,notobjects.Theyare notthesameassubsystems.)Asubsystempresentsastandardsetof interfacestotheoutsideworld,andallaccesstotheobjectsthatcomprise thesubsystemshouldbethroughtheseinterfaces.Ifyouaccessthe subsystemviaasingleobjectwhoseprimaryresponsibilityistoimplement anaccessinterface(s),thatobjectiscalledaport. Packagesarecompiletimethings,subsystemsareruntimethings.Don't confusethemthesimilarnotationisunfortunate.Theclassesthat comprisethesubsystemareoftencontainedinasinglepackage,butneed notbe.(TheclassesthatdefineobjectsintheJDBCsubsystemaredefined inthejava.sqlpackage.I'veshownrelationshipatleft,butthat'snot standardUML.)Subsystemsareidentifiedassuchbya symbol,which canbeplacedinthetaborbodyofthebox. Thediagramatleftshowsboththestandardandballandsocketstyle interfacenotations.UMLalsoletsyouputintotheboxastaticmodel diagramshowingtheclassesthatcomprisethesubsystem.I'vefoundthat levelofdetailtobeunnecessaryinpractice,sohavenotshownit.

www.holub.com/goodies/uml/

2/22

11/26/12

Allen Holub's UML Reference Card

UseCaseDiagram
Specifiesparticipantsinausecaseandtherelationships betweenusecases. Thestickfigurerepresentsaroletakenonbysomeactor (sometimescalledsimply"actor,"butit'sreallyarole). Alineconnectstheactor/roletotheusecaseinwhichit participates.Youmayusecardinality.(ASalesperson placesmanyorders.) Anisspecializationof/generalizesrelationshipbetween actor/roles(denotedby )indicatesadditional responsibilities.(ASupervisorhasalltheresponsibilitiesof aSalesperson,butcanalsoestablishcredit.ASupervisor cancreateanaccount,forexample.) Dottedlinesdenoteusecasedependencies.Common dependenciesare: equivalent Equivalentusecaseshaveidentical activitiesandidenticalflow,butendusers thinkofthemasdifferent.("Deposit"and "Withdrawal"mighthaveidentical activities,thoughtheobjectsinvolved mightbedifferent.) extends Whenextensionextendsbase,allthe activitiesofthebaseusecasearealso performedintheextensionusecase,but theextensionusecaseaddsadditional activitiestoorslightlymodifiesexisting activitiesofthebaseusecase.(To placearecurringorder,youmustperform alltheactivitiesofplacinganorderplus setuptherecurrence.) Ifasetofactivitiesoccurinseveraluse cases,it'sreasonableto"normalize" thesecommonactivitiesoutintoabase usecase,andthenextenditas necessary. HolubExtension:Thisrelationshipis reallyaformofderivation,soIusethe derivationarrow( )insteadofa dashedline.Asinaclassdiagram,the arrowpointsfromtheextensiontothe baseusecase.
includes

Asubcase.Ifcaseincludessubcase, thentheactivitiesofsubcaseare performedoneormoretimesinthecourse ofperformingcase.(An"Authenticate"

www.holub.com/goodies/uml/

3/22

11/26/12

Allen Holub's UML Reference Card

requires follows

resembles

ofperformingcase.(An"Authenticate" subcasemaybeincludedinseverallarger usecases,forexample.)Thesubcaseis usuallyrepresentedintheusingusecase asasingleboxmarkedwiththesubcase nameandthestereotypeusecase. Iffollowerrequiresleader,thenleader mustbecompletedbeforeyoucan executethefollowerusecase.(Youmust createanaccountbeforeyoucanplace anorder.) Twousecasesareverysimilar,butdo havedifferentactivities.

Actors/rolesaremostlyuninterestingtoprogrammers.The dependenciesarevaluableindeterminingwhichusecaseto implementfirst.(Ioftenimplementtheusecasesthathavethe mostincomingarrowsfirst,sinceotherusecasesdependon them.)

ActivityandStateDiagrams
Statediagramssharemanynotationalelementswithactivitydiagrams.Themaindifferenceisthatstatediagrams "decorate"thetransitions(directedlinesbetweenstates)toindicatethemethodcallorconditionthatcausedthe transition. StartingandStopping.Thesolidcircleindicatesthebeginningof thesequenceofactivities. ThecirclewithanXrepresentsanendofa"flow"butnottheend oftheentireusecase.Inotherwords,somesubtaskcompletes, buttheentireusecaseisnotyetcomplete. The"target"indicatesthattheentireusecaseiscomplete.

Subcase(SubActivity).The"rake"symbolindicatesthatthe "activity"iscomplexenoughtomerititsownactivitydiagram.In usecaseanalysis,thisisa"subcase"astandaloneactivitythat occursinmorethanoneusecasebutisnotlargeenoughtobea usecaseinitsownright.

Synchronization(Fork/Join).Usedeitherwhenseveralactivities cangooninparallelorwhentheorderinwhichasetofactivities executeisimmaterial.Theheavybaratthetopisafork.Afterthe fork,allactivitiescan(butarenotrequiredto)gooninparallel. Progresscannotcontinuepastthebaronthebottom(thejoin)until alltheactivitiesthatfeedintothejoincomplete. Youcanlabelthejoinwithaconstraint(e.g.{joinspec=(Aand B)orC})tospecifytheconditionthatallowsprogresstocontinue.


www.holub.com/goodies/uml/ 4/22

11/26/12

Allen Holub's UML Reference Card

B)orC})tospecifytheconditionthatallowsprogresstocontinue. Ifthere'snoconstraint,ANDisassumed.

Guards(tests).Thispathisusedonlyifthetextinthebracketsis true.

Decision(Branch/Merge).Adecisionactivity,theguardlabels thedecisionthatwasmade.Thediamondwithoutgoingarrows (thebranch)specifiesanORoperation,withaconditionimposed bytheguard.Thediamondwithincomingarrows(amerge)simply providesanendtotheORoperation.Amergecanoccurwithout anassociatedbranchifthediagramhasmultiplestartstates.

Signals(Events). Generatingsignals:senttooutsideprocess(RequestPayment atleft). Acceptingsignals:receivedfromoutsideprocess(Payment Receivedatleft). Timersignals:receivedwhentimeelapsesorasettimearrives (30days...atleft).

Exceptions.Extraordinaryerrorsthatyoutypicallydon'tdetect withexplicittestsareindicatedwitha"lightningbolt."

www.holub.com/goodies/uml/

5/22

11/26/12

Allen Holub's UML Reference Card

ObjectFlow.Identifiesobjectsthatarecreatedbyactivities(box withoutgoingarrow)orusedbyactivities(boxwithincoming arrow). Intheexampleatleft,Theinvoiceobjectiscreatedduringthe receiveinvoiceactivityandusedbytheprocessinvoiceactivity. Thecheckobjectiscreatedinthecutcheckactivityandisused bythesendpaymentactivity.Inthissecondcase,youcanalso putboxesatbothendsoftheline. Youcanindicateexactlyhowtheobjectisusedwithaconstraint. (e.g.{create},{store},etc.) SwimLanes.Activitiesarearrangedintoverticalorhorizontal zonesdelimitedwithlines.Eachzonerepresentsabroadareaof responsibility,typicallyimplementedbyasetofclassesor objects.Forexample,theswimlanelabeledaccountingcould representobjectsofseveralclasses(Bookkeeper,Clerk, MailRoom,Accountant)workinginconcerttoperformthesingle "cutpaycheck"activity. UML2.x(bottomdiagramatleft)usessolidratherthandashed lines,andpermitsbothhorizontalandvertical(orboth) delimitation.Theupperleftquadrantinthediagramatleft representsaccountingactivitiesthathappeninParis.

ExampleActivityDiagram

www.holub.com/goodies/uml/

6/22

11/26/12

Allen Holub's UML Reference Card

StaticModel(Class)Diagram
DesignPattern(Collaboration) ThedashedcircleisUML,ver.1.5.ThegreyboxisErich Gamma'snotation,aspresentedinJohnVlissides'book PatternHatching(Reading:AddisonWesley,1998).Use oneortheother. Asingleclasscanhavedifferentroleswithrespectto severalpatterns.Inthebottomexample,theclassserves asboththe"ConcreteObserver"inthe"Observer"pattern andalsothe"RealSubject"inthe"Proxy"pattern.The UMLnotationcanidentifyallparticipatingclassesifthey happentobeinphysicalproximity.

www.holub.com/goodies/uml/

7/22

11/26/12

Allen Holub's UML Reference Card

Classes.Standardrepresentationcontainsthreecompartments: 1. Thenamecompartment(required)containstheclass nameandotherdocumentationrelatedinformation:E.g.: Sm_ls btat oecas asrc {ato: uhr Gog Jto ere esn mdfe: oiid 1//99 0629 cekdot y hce_u: } Guillemetsidentifystereotypes.E.g.:utility, abstractinterface. Canuseagraphicinsteadofword.(interface oftenrepresentedassmallcircle) Accessprivileges(seebelow)canprecedename Useitalicsforabstractclassandinterfacenames. 2. Theattributescompartment(optional): DuringAnalysis:identifytheattributes(i.e.defining characteristics)oftheobject. DuringDesign:identifyarelationshiptoastock class: This:

isamorecompact(andlessinformative)versionof this:

Everythingexceptconstantvaluesmustbeprivate. Always.Period. 3. Theoperationscompartment(optional)containsmethod definitions: msaenm(ruet) rtr_ye esg_aeagmns: euntp Resistthetemptationtouseimplementationlanguage syntax.

www.holub.com/goodies/uml/

8/22

11/26/12

Allen Holub's UML Reference Card

Visibility(accessprivileges)indicatedasfollows:1 + public # protected ~ package2 private implementationvisibility(inaccessibletoother objects)2 (+)forcedpublic.Overrideofaninterfacemethodthat shouldbetreatedasprivate,evenifit'sdeclared public.2 UML2.0permitsC++stylegrouping: pbi ulc a) it (: n b) vi (: od piae rvt c) vi (: od Properties(newinUML2.0.): / Derivedattribute.Synthesizedatruntime. Combinewithaccess.(e.g.height,width, /+area) {property} Standardpropertiesare:{readOnly},{union}, {subsetspropertyname}, {redefinespropertyname},{ordered},{bag}, {seq}(or{sequence}),{composite}. example:/+area:integer{readOnly}

a s r c operationsindicatedbyitalics(orunderline). btat
Ifattributesandoperationsarebothomitted(yieldingaboxwitha classnameinit),amorecompletedefinitionisassumedtobeon anothersheet. Introducenonstandardcompartmentssimplybynamingthem,as isshowninthebottomexampleatleft. 1Java,unfortunately,defaultsto"package"accesswhenno modifierispresent.UMLdoesnotsupportthenotionofadefault access.UMLhasnonotionof"implementationvisibility" (accessibleonlywithinanobjectotherobjectsofthesame classcannotaccessit). 2TheseareAllenHolub'spersonalextensions.The~was incorporatedintotheUMLstandardwithversion1.5.Theother's arenotstandardUML. Associations(relationshipsbetweenclasses). Associatedclassesareconnectedbylines. Therelationshipisidentified,ifnecessary,witha<or> toindicatedirection(orusesolidarrowheads).

www.holub.com/goodies/uml/

9/22

11/26/12

Allen Holub's UML Reference Card

Therolethataclassplaysintherelationshipisidentified onthatclass'ssideoftheline. Stereotypes(likefriend)areappropriate. Unidirectionalmessageflowcanbeindicatedbyanarrow (butisimplicitinsituationswherethereisonlyonerole): Cardinality: 1 (usuallyomittedif1:1)

n (unknownatcompiletime,butbound) 0..1(1..21..n) 1..* (1ormore) * (0ormore) Example:

casCmay ls opn {piaePro[ epoe=e Pro[] rvt esn] mlyenw esnn; pbi vi gv_earie ulc od iem__as( Pro epoe) esn mlye {/../ *.* } pbi vi hr_e Pro popc ) ulc od iem( esn rset {/../ *.* } } casPro ls esn { piaeSrn nm; rvt tig ae piaeCmayepoe; rvt opn mlyr piaePro bs; rvt esn os piaeVco fuke=e Vco(; rvt etr lnisnw etr) pbi vi ulc od yur_ie({.} o_efrd).. } (AJavaV c o isavariablelengtharray.Inthiscaseitwill etr holdP r o objects.) esn ImplementationInheritance(Generalize/Specialize) identifiesimplementationinheritance(e t n s x e d inJava) Thebaseclassisaconcreteclass,withdataormethodsdefined init,ascomparedtoaninterface,whichispurelyabstract(in C++,aclassmadeofnothingbutp r v r u l u e i t a methods). Thederivedclassisthebaseclass,butwithadditionalor
www.holub.com/goodies/uml/ 10/22

11/26/12

Allen Holub's UML Reference Card

Thederivedclassisthebaseclass,butwithadditionalor modifiedproperties.Thederived(sub)classisaspecializationof thebase(super)class.Variationsinclude:

InterfaceInheritance(Specifies/Refines/Implements). Aninterfaceisacontractthatspecifiesasetofmethodsthat mustbeimplementedbyaderivedclass(inC++,aclass containingnothingbutpurevirtualmethods.JavaandC#support themdirectly).(C.f.abstractclass,whichcancontainmethod andfielddefinitionsinadditiontotheabstractdeclarations.An abstractclassisextended(seeimplementationinheritance). Interfacescontainnoattributes,sothe"attributes"compartment isalwaysempty. Indicateaninterfaceinheritancerelationship(i p e e t in mlmns Java)withadashedline.Thatis,useadashedlinewhenthe baseclassisaninterfaceandthederivedclassisaconcrete classthatimplementsthemethodsdefinedintheinterface. Wheninterfacesextendotherinterfaces,useasolidline. The"ballandsocket"notationatleftisnewinUML2.0.Classes thatconsume(require)aninterfacedisplaya"socket"labeled withtheinterfacename(Aatleft).Classesthatprovide (implement)aninterfacedisplaya"ball"labeledwiththeinterface name(Batleft).Combiningthetwoisacompactwaytosaythat theConsumertalkstotheproviderviathenamedinterface. MyUMLextension:Roundedcornersidentify interfaces.Sinceroundedcornersareoften difficulttodrawbyhand,Isometimesusethe versionatrightforhanddrawndiagrams. StrictUMLusestheinterfacestereotypein thenamecompartmentofastandardclassbox. Asmallcircleinacornerofthecompartment oftenindicatesaninterface,aswell.

www.holub.com/goodies/uml/

11/22

11/26/12

Allen Holub's UML Reference Card

Ifthefullinterfacespecificationisinsomeotherdiagram,Iuse the"ball"notationor Microsoftstyle"pin"notation(atright) isobsoleteasofUML2.0.Don'tuse it. Nesting,InnerClass..Identifiesnesting(containment) relationshipsinalldiagrams.Inaclassdiagram:an"inner"class whosedefinitionisnestedwithinthe"outer"classdefinition. Typicallyputstheinnerclassinthenamespaceoftheouter class,butmayhaveadditionalproperties. .

Dependency.UserusesResource,butResourceisnota memberof(fieldin)theUserclass.IfResourceismodified, somemethodofUsermightneedtobemodified.Resourceis typicallyalocalvariableorargumentofsomemethodinUser. Thelineistypicallystereotyped(e.g.createsmodifies) Aggregation(comprises)relationshiprelationship.1Destroying the"whole"doesnotdestroytheparts. Composition(has)relationship.1Thepartsaredestroyedalong withthe"whole."Doesn'treallyexistinJava.InC++: casCnanr ls otie { Ie ie1 tm tm; / bt o teeae / oh f hs r Ie *tm; / "opsto" tm ie2 / cmoiin pbi: ulc Cnanr){ie2=nwIe;} otie( tm e tm ~otie({dlt ie2 Cnanr) eee tm; } } NavigabilityMessagesflowindirectionofarrow(only).An unmarkedlineis"unspecified"navigability.AnXindicatesnon navigable(Uml2.0). Typically,ifaroleisspecified,thennavigabilityinthedirectionof thatroleisimplicit.Ifanobjectdoesn'thavearoleinsome relationship,thenthere'snowaytosendmessagestoit,sonon navigabilityisimplicit. ConstraintAconstrainedrelationshiprequiressomeruletobe applied.(e.g.{ordered})Oftencombinedwithaggregation, composition,etc. ComplexConstraint Comments

www.holub.com/goodies/uml/

12/22

11/26/12

Allen Holub's UML Reference Card

Inthecaseoftheor,onlyoneoftheindicated relationshipswillexistatanygivenmoment(aC++ uin n o ). Subsetdoestheobvious. InofficialUML,putarbitraryconstraintsthataffectmore thanonerelationshipina"comment"box,asshown.I usuallyleaveoutthebox.

QualifiedAssociation(hashtable,associativearray, "dictionary").Useanexternal(or"foreign")keytoidentifyan objectthatdoesnotcontainthatkey.Eg.:Abankusesa CustomertoidentifyanAccountbecauseaccountsdonot containcustomers.(Anaccountisidentifiedbyanaccount number,notacustomer.) casUe ls sr {/ AHstbei a ascaieary / ahal s n soitv ra, / idxdb sm kyadcnann / nee y oe e n otiig / sm vle i ti cs,cnan / oe au; n hs ae otis / Ie ojcs idxdb UD / tm bet, nee y I. piaeHstbebg=nwHsTbe) rvt ahal a e ahal(; piaevi adUDky Ie vle rvt od d(I e, tm au) { bgpt ky vle) a.u( e, au ; } } AssociationClass Usewhenaclassisrequiredtodefinearelationship. Ifthisclassappearsonlyasanassociationclass(an classtoclassassociationliketheonebetweenPerson andTicketdoesn'texist),objectsoftheassociationclass mustbepassedasargumentstoeverymessage.

ExampleClassDiagram
www.holub.com/goodies/uml/ 13/22

11/26/12

Allen Holub's UML Reference Card

Interaction(DynamicModel)Diagrams
"Interaction"diagramsshowthe"dynamicmodel."Theyshowhowobjectsinteractatruntime:how theyactoutausecasebysendingmessagestoeachother. Therearetwosortsofinteractiondiagrams:SequenceDiagramsandCollaboration/Communication Diagrams.Thetwoformspresentidenticalinformationindifferentway.Whichoneyouuseislargely amatteroftaste.Sequencediagramstendtobemorereadable,collaborationdiagramsaremore compact.

www.holub.com/goodies/uml/

14/22

11/26/12

Allen Holub's UML Reference Card

SequenceDiagram
WithoutActivations: ObjectsandMessages Verticallinesrepresentobjects,notclasses. Mayoptionallyadda":class"totheboxifitmakesthe diagrammorereadable. representssynchronousmessage.(messagehandler doesn'treturnuntildone). representsreturn.Labelarrowwiththename[and optional:type]ofthereturnedobject.(Exampleatleft translatesto: rtre_b=eevrmsae(; eundojrcie.esg2)) Sendingobject'sclassmusthave: 1. Aassociationofsomesortwithreceivingobject's class. 2. Thereceiversideclass's"role"mustbethesameas thenameofthereceivingobject. Activiationsareoptional,butmucheasiertoread.Compare:

WithActivations:

to

Returnimpliedbybottomofboxwhenactivationspresent.A isunnecessaryonmethodsthatdon'treturnvalues. Explicitreturns,whenshown,areunambiguousbecausethey emitfromtheactivationforthemessagethatreturnsthe value. Messagesthattakealongtimetoarrive(whensent overanetworkforexample)canbedrawnwitha diagonalline,asisshownatright. Whenactivationsaremissing,returnarrowsareessentialfor disambiguatingcontrolflow.Inabove diagram,it'sunclearwhether m s a e orm s a e returns esg2 esg4 r t r e _ b whenunlabeled eundoj returnsareomitted. Whendrawingbyhand,Iuseasolid lineandputtheactivationboxesat thesideoftheline,asisshownat right. Data"Tadpoles" Data"tadpoles"areoftenmorereadablethanreturnarrowsor messagearguments.Atleft,thee t y l r objectsendsthe nrCek s i p n D c anobjectcalledo d r hpigok r e .Thes i p n D c hpigok returnsthes i p n R c i t h p i g e e p object.

www.holub.com/goodies/uml/

15/22

11/26/12

Allen Holub's UML Reference Card

ObjectCreation Nameboxappearsatpointofcreation. createsformforautomaticcreation.InC++:Anobject(not areferencetoone)isdeclaredasafieldinaclass.The closestJavaequivalentisanobjectcreatedbyinstance variableinitialization: casX ls {piaeCso=nwCs) rvt l e l(; /.. /. } Ifmessageshowninsteadofcreates,thenthemessage handlercreatestheobject.Thinkofn w F e ( as e rd) F e . e ( .Methoddoesnothavetoben w ) rdnw) e(. Conditions,Branches,Loops,Grouping 1. m s a e ( issentonlyiftheconditionspecifiedinthe esg1) guard(inbrackets)istrue. 2. Abranch.Sendersendseitherm s a e ( or esg2) m s a e ( .Guardsshouldbeexclusive.Iuseelse esg3) insteadofaguardwhenappropriate. 3. Iteration.Sendersendsm s a e ( aslongasthe esg4) conditionistrue. 4. "Foreach."Ifthereceiverisacollectionofobjects(indicated bythecardinalityoftheassociatedroleinthestaticmodel), sendthemessagetoallofthem. 5. UML2.0InteractionFrame.Asshown,conditionspecifiesa loop.Canalsouse: lo o p Aloop,executesmultipletimes Optional.An"if"statement. ot p r g o Anamedregion. ein Areferencetoanamedregion(elsewherein rf e diagramoronanotherdiagram):

6. Asshown,anif/elsestructure.Canuse: Executeoneofthealternatives,controlledby at l guards Executeregionsinparallel pr a

www.holub.com/goodies/uml/

16/22

11/26/12

Allen Holub's UML Reference Card

Interactionframescannest:

Alternative(Nonstandard)Branch/LoopNotationUse"pseudo activations"andguardstoindicatecontrolflow. Diagonallineindicatesan"alternative"flow.

Loops,Alternative(MyownextensiontoUML.) Don'tthinkloops,thinkwhattheloopisaccomplishing. Typically,youneedtosendsomesetofmessagestoevery elementinsomecollection.Dothiswithevery. Youcangetmoreelaborate:"everyreceiverwherex y < ". Thediagramatleftcomesfromthismodel:

andmapstothefollowingcode: cassne_ls ls edrcas { rcie_ls rcie[] eevrcas eevrn; pbi d_t) ulc oi( { fr iti=0 i<n +i) o( n ; ; + rcie[]msae) eevri.esg(; } } ActiveObjects Activeobjectsprocessmessagesononeormoreauxiliary backgroundthreads.Theyareareindicatedbyaheavyweightoutline. Themessagessenttoanactiveobjectaretypicallyasynchronous: theyinitiatesomeactivitybutdon'twaitaroundfortheactivityto complete. Thestickarrowheadmeansasynchronousmessagethe callreturnsbeforemessageisfullyprocessed.Areturnvalue fromanasynchronousmessagecanindicatethatwork

www.holub.com/goodies/uml/

17/22

11/26/12

Allen Holub's UML Reference Card

started,butcan'tindicateanysortofcompletionstatus. Theboxonthelifelinemeansactivatedsomeactivityis beingperformedbytheobject,perhapsonabackground thread. Aseparatelifeline[shownatleftwhenthew r ( message ok) activatesthep o e s r r c s o object]impliesaseparatethread forprocessingthemessage. ThelargeXindicatesthatanobjectdeletesitselfwhendone handlingmessage.Anexternalkillisrepresentedas: Atleft,thep o e s x messageactivatesp o e s r rcs() r c s o .The p o e s x messageisasynchronous,sotherequestingmethod rcs() returnsimmediatelyandthep o e s r r c s o objectdoestheworkin thebackground.Whilep o e s x isbeinghandled,the rcs() s n e objectsendsad ( ) edr o x message,whichbringsan anonymousW r e objectintoexistence.(Thed ( methodisa okr o) s a i methodoftheW r e classthatcreatesananonymous ttc okr objecttohandletherequest.)Thisanonymousobjectdoessome work,sendingasynchronousw r ( messagetothe ok) poesr r c s o object.Sincethew r ( handlerissynchronous,it ok) doesn'treturnuntiltheworkiscomplete.Theanonymousworker waitsforw r ( toreturn,thendeletesitself(killingany ok) associatedthreads).Thep o e s r r c s o objectcontinuestoexist, waitingforsomethingelsetodo.

Callbacks,Recursion Atleft,thesendersendsanasynchronousmessagetotheactive objectr c i e forbackgroundprocessing,passingittheobject eevr tonotifywhentheoperationiscomplete(inthiscase,itself).The r c i e callsit'sownm g . . methodtoprocessthe eevr s(.) request,andthatmethodissuesthec l b c ( callwhenit's alak) done.Notethat: Thec l b c ( messageisrunningonther c i e alak) eevr object'smessageprocessingthread. Thec l b c ( methodis,however,amemberofthe alak) s n e object'sclass,sohasaccesstoallthefieldsofthe edr s n e object. edr Sincetheoriginalthread(fromwhichtheoriginal rqet) e u s ( wasissued)isalsorunning,youmust synchronizeaccesstoallfieldssharedbyboth c l b c ( andothermethodsofthes n e object. alak) edr

www.holub.com/goodies/uml/

18/22

11/26/12

Allen Holub's UML Reference Card

MessageArrowheads Symbol Message Description Type Asynchronous Thehandlerreturnsimmediately,buttheactualworkisdoneinthebackground.Thesender canmoveontoothertaskswhileprocessinggoeson. Synchronous Thesenderwaitsuntilthehandlercompletes(blocks).Thisisanormalmethodcallina singlethreadedapplication. Asynchronous Obsolete(UMLversion1.3orearlier.) Balking Thereceivingobjectcanrefusetoacceptthemessagerequest.Thiscouldhappenifan "active"object'smessagequeuefills,forexample.Notpartof"core"UML. Timeout Themessagehandlertypicallyblocks,butwillreturnafterapredeterminedamountoftime, eveniftheworkofthehandlerisnotcomplete.Notpartof"core"UML.

ExampleSequenceDiagram

www.holub.com/goodies/uml/

19/22

11/26/12

Allen Holub's UML Reference Card

Collaboration(Communication)Diagram
Collaboration(renamed"Communication"inUML2)Diagrams areanalternativepresentationofasequencediagram.They tendtobemorecompact,buthardertoread,thanthe equivalentsequencediagrams.Theexampleatleftisidentical inmeaningtotheSequenceDiagramexampleattheendofthe previoussection.(Itrepresentsthesameobjectsandmessage flow.) Theboxesareobjects.Linesconnectingtwoboxesindicates thattheobjectscollaboratewith(sendmessagesto)one another.Useamultiplicityindicatorinthebox(suchas*)to indicatethatallelementsofanaggregationreceiveamessage. Theobjectnametypicallygoesinsidethebox,butcango outsidetheboxwhendifferentcollaboratorsrefertoitby differentnames.E.g.:theJ o p n n atthelowerrightof Cmoet thediagramisreferencedbyE e e t l m n objectsthroughafield calledp o y r x it'sreferencedfromt i g i viaafield hn[] nameda t i u e u . trbt_i Usethefollowingqualifiersonnames:
parametername localname name{new} name{destroyed} name{transient}

Methodparameter. Localvariable. Objectcreatedduringexecution Objectdestroyedduringexecution Objectcreatedduringexecution,used, thendestroyed

Usually,theinstancename(orreferencethroughwhichthe instanceisaccessed)isthesameastheroletheinstance playsinthecollaboration.Whenthenameandrolearen't identical,useinstance/role:Class.E.g.:given t t r t a h r P r o and uo/ece:esn lcue/ece:esn e t r r t a h r P r o ,anobjectofclassPerson, usedintheroleofteacher,iscalledt t r u o insomeportionof thecodeandl c u e elsewhereinthecode. etrr Messagesthatflowfromoneobjecttoanotheraredrawnnext totheline,withanarrowindicatingdirection.Arrowheadtypes havethesamemeaningasinsequencediagrams.The messagesequenceisshownviaanumberingscheme. Message1issentfirst.Messages1.1,1.2,etc.,aresentby whatevermethodhandlesmessage1.Messages1.1.1,1.1.2, etc.,aresetbythemethodthathandlesmessage1.1,andso forth.Messagesequenceinthecurrentexampleis: 1. 1.1 1.1.1 1.1.2 1.1.2.1 1.1.2.2

www.holub.com/goodies/uml/

20/22

11/26/12

Allen Holub's UML Reference Card

1.1.3 2. 2.1 2.2 2.2.1 2.2.2 3. Guardsarespecifiedusingthe"ObjectConstraintLanguage,"a pseudocodethat'spartoftheUMLspecification. Syntactically,it'smorelikePascalandAdathanJavaand C++,butit'sreadableenough.(Theoperatorsthatwilltripyou upareassignment[: ]equality[= = ]andnotequals[< ]).Asin > asequencediagram,anasteriskindicatesiteration.

Nomeclature
Therearethreebroadcategoriesofdiagrams. StructureDiagrams includeclassdiagrams,deploymentdiagrams,etc. BehaviorDiagrams includeactivity,usecase,andstatediagrams. InteractionDiagrams(areasubclassofBehaviorDiagrams) includeSequenceandCollaborationdiagrams. Collaborationdiagramsarecalled"CommunicationDiagrams"inUML2.

What'sMissing
AfewpartsofUMLaren'tshownhere.(Someoftheseareuseful,Ijusthaven'tgottenaroundto addingthemyet.) StateDiagramSymbols.Thereareafewsymbolsusedinstatediagramsthataren'tshown intheearlierActivity/StateDiagramsection. Deploymentdiagrams.Showhowlargemodulesinthesystemhookup.Usefulprimarilyfor marketingpresentations,executivesummaries,andpointyhairedbosses. ParameterizedClasses.C++templates/Javagenerics. NaryAssociations.arebetterdonewithclasses.Don'tusethem. ComponentDiagrams.Theonlydifferencebetweenacomponentandasubsystemissize. Componentdiagramsarealmostidenticaltosubsystemdiagrams. ActivityRealizationDiagram.isanactivitydiagramredrawntolookmorelikea collaborationdiagram. RefertotheUMLSuperstructuredocumentformoredetails.

Footnotes
(1)Compositionvs.Aggregation: Neither"aggregation"nor"composition"reallyhavedirectanalogsinmanylanguages(Java,for example).

www.holub.com/goodies/uml/

21/22

11/26/12

Allen Holub's UML Reference Card

An"aggregate"representsawholethatcomprisesvariouspartsso,aCommitteeisanaggregateof itsMembers.AMeetingisanaggregateofanAgenda,aRoom,andtheAttendees.At implementationtime,thisrelationshipisnotcontainment.(Ameetingdoesnotcontainaroom.) Similarly,thepartsoftheaggregatemightbedoingotherthingselsewhereintheprogram,sothey mightbereferencedbyseveralobjects.Inotherwords,There'snoimplementationleveldifference betweenaggregationandasimple"uses"relationship(an"association"linewithnodiamondsonitat all).Inbothcasesanobjecthasreferencestootherobjects.Thoughthere'snoimplementation difference,it'sdefinitelyworthcapturingtherelationshipintheUML,bothbecauseithelpsyou understandthedomainmodelbetter,andbecausetherearesubtleimplementationissues.Imight allowtightercouplingrelationshipsinanaggregationthanIwouldwithasimple"uses,"forexample. Compositioninvolveseventightercouplingthanaggregation,anddefinitelyinvolvescontainment. Thebasicrequirementisthat,ifaclassofobjects(callita"container")iscomposedofotherobjects (callthemthe"elements"),thentheelementswillcomeintoexistenceandalsobedestroyedasa sideeffectofcreatingordestroyingthecontainer.Itwouldberareforaelementnottobedeclaredas piae r v t .AnexamplemightbeanCustomer'snameandaddress.ACustomerwithoutanameor addressisaworthlessthing.Bythesametoken,whentheCustomerisdestroyed,there'snopointin keepingthenameandaddressaround.(Comparethissituationwithaggregation,wheredestroying theCommitteeshouldnotcausethememberstobedestroyedtheymaybemembersofother Committees). Intermsofimplementation,theelementsinacompositionrelationshiparetypicallycreatedbythe constructororaninitializerinafielddeclaration,butJavadoesn'thaveadestructor,sothere'sno waytoguaranteethattheelementsaredestroyedalongwiththecontainer.InC++,theelement wouldbeanobject(notareferenceorpointer)that'sdeclaredasafieldinanotherobject,socreation anddestructionoftheelementwouldbeautomatic.Javahasnosuchmechanism.It'snonetheless importanttospecifyacontainmentrelationshipintheUML,becausethisrelationshiptellsthe implementation/testingfolksthatyourintentisfortheelementtobecomegarbagecollectible(i.e. thereshouldbenoreferencestoit)whenthecontainerisdestroyed).
AllenI.Holub&Associates Berkeley,California510.528.3620
2011AllenI.Holub( www.holub.com ).AllRightsReserved.

www.holub.com/goodies/uml/

22/22

You might also like