Вы находитесь на странице: 1из 10

1/9/13

Practical UML: A HandsOn Introduction for Developers

PracticalUML :AHandsOnIntroductionfor Developers


By:RandyMiller Abstract:ThistutorialprovidesaquickintroductiontotheUnifiedModelingLanguage Theheartofobjectorientedproblemsolvingistheconstructionofamodel.Themodelabstracts theessentialdetailsoftheunderlyingproblemfromitsusuallycomplicatedrealworld.Several modelingtoolsarewrappedundertheheadingofthe UML,whichstandsforUnifiedModeling Language.ThepurposeofthiscourseistopresentimportanthighlightsoftheUML. AtthecenteroftheUMLareitsninekindsofmodelingdiagrams,whichwedescribehere. Usecasediagrams Classdiagrams Objectdiagrams Sequencediagrams Collaborationdiagrams Statechartdiagrams Activitydiagrams Componentdiagrams Deploymentdiagrams Someofthesectionsofthiscoursecontainlinkstopageswithmoredetailedinformation.And everysectionhasshortquestions.Usethemtotestyourunderstandingofthesectiontopic. WhyisUMLimportant? Let'slookatthisquestionfromthepointofviewoftheconstructiontrade.Architectsdesign buildings.Buildersusethedesignstocreatebuildings.Themorecomplicatedthebuilding,the morecriticalthecommunicationbetweenarchitectandbuilder.Blueprintsarethestandard graphicallanguagethatbotharchitectsandbuildersmustlearnaspartoftheirtrade. Writingsoftwareisnotunlikeconstructingabuilding.Themorecomplicatedtheunderlyingsystem, themorecriticalthecommunicationamongeveryoneinvolvedincreatinganddeployingthe software.Inthepastdecade,theUMLhasemergedasthesoftwareblueprintlanguagefor analysts,designers,andprogrammersalike.Itisnowpartofthesoftwaretrade.TheUMLgives everyonefrombusinessanalysttodesignertoprogrammeracommonvocabularytotalkabout softwaredesign. TheUMLisapplicabletoobjectorientedproblemsolving.AnyoneinterestedinlearningUMLmust befamiliarwiththeunderlyingtenetofobjectorientedproblemsolvingitallbeginswiththe constructionofamodel.A modelisanabstractionoftheunderlyingproblem.The domainisthe actualworldfromwhichtheproblemcomes. Modelsconsistof objectsthatinteractbysendingeachother messages.Thinkofanobjectas "alive."Objectshavethingstheyknow(attributes)andthingstheycando(behaviorsor operations).Thevaluesofanobject'sattributesdetermineits state. Classesarethe"blueprints"forobjects.Aclasswrapsattributes(data)andbehaviors(methodsor functions)intoasingledistinctentity.Objectsare instancesofclasses.

edn.embarcadero.com/print/31863

1/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Usecasediagrams
Usecasediagramsdescribewhatasystemdoesfromthestandpointofanexternalobserver.The emphasisison whatasystemdoesratherthan how. Usecasediagramsarecloselyconnectedtoscenarios.A scenarioisanexampleofwhathappens whensomeoneinteractswiththesystem.Hereisascenarioforamedicalclinic. "Apatientcallstheclinictomakeanappointmentforayearlycheckup.Thereceptionistfinds thenearestemptytimeslotintheappointmentbookandschedulestheappointmentforthat timeslot." A usecaseisasummaryofscenariosforasingletaskorgoal.An actoriswhoorwhatinitiates theeventsinvolvedinthattask.Actorsaresimplyrolesthatpeopleorobjectsplay.Thepicture belowisa MakeAppointmentusecaseforthemedicalclinic.Theactorisa Patient.The connectionbetweenactorandusecaseisa communicationassociation(or communicationfor short).

Actorsarestickfigures.Usecasesareovals.Communicationsarelinesthatlinkactorstouse cases. Ausecasediagramisacollectionofactors,usecases,andtheircommunications.We'veput Make Appointmentaspartofadiagramwithfouractorsandfourusecases.Noticethatasingleuse casecanhavemultipleactors.

Usecasediagramsarehelpfulinthreeareas. determiningfeatures(requirements).Newusecasesoftengeneratenewrequirementsas thesystemisanalyzedandthedesigntakesshape. communicatingwithclients.Theirnotationalsimplicitymakesusecasediagramsagood wayfordeveloperstocommunicatewithclients. generatingtestcases.Thecollectionofscenariosforausecasemaysuggestasuiteof testcasesforthosescenarios.

Classdiagrams
edn.embarcadero.com/print/31863 2/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

AClassdiagramgivesanoverviewofasystembyshowingitsclassesandtherelationships amongthem.Classdiagramsarestatictheydisplaywhatinteractsbutnotwhathappenswhen theydointeract. Theclassdiagrambelowmodelsacustomerorderfromaretailcatalog.Thecentralclassisthe Order.Associatedwithitarethe Customermakingthepurchaseandthe Payment.A Paymentis oneofthreekinds: Cash, Check,or Credit.Theordercontains OrderDetails(lineitems),each withitsassociated Item.

UMLclassnotationisarectangledividedintothreeparts:classname,attributes,andoperations. Namesofabstractclasses,suchas Payment,areinitalics.Relationshipsbetweenclassesarethe connectinglinks. Ourclassdiagramhasthreekindsofrelationships. associationarelationshipbetweeninstancesofthetwoclasses.Thereisanassociation betweentwoclassesifaninstanceofoneclassmustknowabouttheotherinorderto performitswork.Inadiagram,anassociationisalinkconnectingtwoclasses. aggregationanassociationinwhichoneclassbelongstoacollection.Anaggregationhas adiamondendpointingtothepartcontainingthewhole.Inourdiagram, Orderhasa collectionof OrderDetails. generalizationaninheritancelinkindicatingoneclassisasuperclassoftheother.A generalizationhasatrianglepointingtothesuperclass. Paymentisasuperclassof Cash, Check,and Credit. Anassociationhastwoends.Anendmayhavea rolenametoclarifythenatureofthe association.Forexample,an OrderDetailisalineitemofeach Order. A navigabilityarrowonanassociationshowswhichdirectiontheassociationcanbetraversedor queried.An OrderDetailcanbequeriedaboutits Item,butnottheotherwayaround.Thearrow alsoletsyouknowwho"owns"theassociation'simplementationinthiscase, OrderDetailhasan Item.Associationswithnonavigabilityarrowsarebidirectional. The multiplicityofanassociationendisthenumberofpossibleinstancesoftheclassassociated withasingleinstanceoftheotherend.Multiplicitiesaresinglenumbersorrangesofnumbers.In ourexample,therecanbeonlyone Customerforeach Order,buta Customercanhaveany numberof Orders.
edn.embarcadero.com/print/31863 3/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Thistablegivesthemostcommonmultiplicities. Multiplicities 0..1 0..*or * 1 1..* Meaning zerooroneinstance.Thenotation n..mindicates nto minstances. nolimitonthenumberofinstances(includingnone). exactlyoneinstance atleastoneinstance

Everyclassdiagramhasclasses,associations,andmultiplicities.Navigabilityandrolesare optionalitemsplacedinadiagramtoprovideclarity.

Packagesandobjectdiagrams Tosimplifycomplexclassdiagrams,youcangroupclassesinto packages.Apackageisa collectionoflogicallyrelatedUMLelements.Thediagrambelowisabusinessmodelinwhichthe classesaregroupedintopackages.

Packagesappearasrectangleswithsmalltabsatthetop.Thepackagenameisonthetaborinside therectangle.Thedottedarrowsare dependencies.Onepackagedependsonanotherifchanges intheothercouldpossiblyforcechangesinthefirst. Objectdiagramsshowinstancesinsteadofclasses.Theyareusefulforexplainingsmallpieces withcomplicatedrelationships,especiallyrecursiverelationships. Thissmallclassdiagramshowsthatauniversity Departmentcancontainlotsofother Departments.

Theobjectdiagrambelowinstantiatestheclassdiagram,replacingitbyaconcreteexample.
edn.embarcadero.com/print/31863 4/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Eachrectangleintheobjectdiagramcorrespondstoasingleinstance.Instancenamesare underlinedinUMLdiagrams.Classorinstancenamesmaybeomittedfromobjectdiagramsas longasthediagrammeaningisstillclear.

Sequencediagrams Classandobjectdiagramsarestaticmodelviews. Interactiondiagramsaredynamic.They describehowobjectscollaborate. A sequencediagramisaninteractiondiagramthatdetailshowoperationsarecarriedoutwhat messagesaresentandwhen.Sequencediagramsareorganizedaccordingtotime.Thetime progressesasyougodownthepage.Theobjectsinvolvedintheoperationarelistedfromleftto rightaccordingtowhentheytakepartinthemessagesequence. Belowisasequencediagramformakingahotelreservation.Theobjectinitiatingthesequenceof messagesis aReservationwindow.

edn.embarcadero.com/print/31863

5/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

The Reservationwindowsendsa m a k e R e s e r v a t i o n ( ) messagetoa HotelChain.The HotelChainthensendsa m a k e R e s e r v a t i o n ( ) messagetoa Hotel.Ifthe Hotelhasavailable rooms,thenitmakesa Reservationanda Confirmation. Eachverticaldottedlineisa lifeline,representingthetimethatanobjectexists.Eacharrowisa messagecall.Anarrowgoesfromthesendertothetopofthe activationbarofthemessageon thereceiver'slifeline.Theactivationbarrepresentsthedurationofexecutionofthemessage. Inourdiagram,the Hotelissuesa selfcalltodetermineifaroomisavailable.Ifso,thenthe Hotelcreatesa Reservationanda Confirmation.Theasteriskontheselfcallmeans iteration (tomakesurethereisavailableroomforeachdayofthestayinthehotel).Theexpressionin squarebrackets,[],isa condition. Thediagramhasaclarifying note,whichistextinsideadogearedrectangle.Notescanbeput intoanykindofUMLdiagram.

Collaborationdiagrams Collaborationdiagramsarealsointeractiondiagrams.Theyconveythesameinformationas sequencediagrams,buttheyfocusonobjectrolesinsteadofthetimesthatmessagesaresent.In asequencediagram,objectrolesaretheverticesandmessagesaretheconnectinglinks.

edn.embarcadero.com/print/31863

6/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Theobjectrolerectanglesarelabeledwitheitherclassorobjectnames(orboth).Classnamesare precededbycolons(:). Eachmessageinacollaborationdiagramhasa sequencenumber.Thetoplevelmessageis numbered1.Messagesatthesamelevel(sentduringthesamecall)havethesamedecimalprefix butsuffixesof1,2,etc.accordingtowhentheyoccur.

Statechartdiagrams Objectshavebehaviorsandstate.Thestateofanobjectdependsonitscurrentactivityor condition.A statechartdiagramshowsthepossiblestatesoftheobjectandthetransitionsthat causeachangeinstate. Ourexamplediagrammodelstheloginpartofanonlinebankingsystem.Logginginconsistsof enteringavalidsocialsecuritynumberandpersonalidnumber,thensubmittingtheinformationfor validation. Loggingincanbefactoredintofournonoverlappingstates: GettingSSN, GettingPIN, Validating,and Rejecting.Fromeachstatecomesacompletesetof transitionsthatdetermine thesubsequentstate.

edn.embarcadero.com/print/31863

7/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Statesareroundedrectangles.Transitionsarearrowsfromonestatetoanother.Eventsor conditionsthattriggertransitionsarewrittenbesidethearrows.Ourdiagramhastwoself transition,oneon GettingSSNandanotheron GettingPIN. Theinitialstate(blackcircle)isadummytostarttheaction.Finalstatesarealsodummystates thatterminatetheaction. Theactionthatoccursasaresultofaneventorconditionisexpressedintheform / a c t i o n . Whileinits Validatingstate,theobjectdoesnotwaitforanoutsideeventtotriggeratransition. Instead,itperformsanactivity.Theresultofthatactivitydeterminesitssubsequentstate.

Activitydiagrams An activitydiagramisessentiallyafancyflowchart.Activitydiagramsandstatechartdiagrams arerelated.Whileastatechartdiagramfocusesattentiononanobjectundergoingaprocess(oron aprocessasanobject),anactivitydiagramfocusesontheflowofactivitiesinvolvedinasingle process.Theactivitydiagramshowsthehowthoseactivitiesdependononeanother. Forourexample,weusedthefollowingprocess. "WithdrawmoneyfromabankaccountthroughanATM." Thethreeinvolvedclasses(people,etc.)oftheactivityare Customer, ATM,and Bank.The processbeginsattheblackstartcircleatthetopandendsattheconcentricwhite/blackstop circlesatthebottom.Theactivitiesareroundedrectangles.

edn.embarcadero.com/print/31863

8/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Activitydiagramscanbedividedintoobject swimlanesthatdeterminewhichobjectisresponsible forwhichactivity.Asingle transitioncomesoutofeachactivity,connectingittothenextactivity. Atransitionmay branchintotwoormoremutuallyexclusivetransitions. Guardexpressions (inside[])labelthetransitionscomingoutofabranch.Abranchanditssubsequent merge markingtheendofthebranchappearinthediagramashollowdiamonds. Atransitionmay forkintotwoormoreparallelactivities.Theforkandthesubsequent joinofthe threadscomingoutoftheforkappearinthediagramassolidbars.

Componentanddeploymentdiagrams
A componentisacodemodule.Componentdiagramsarephysicalanalogsofclassdiagram. Deploymentdiagramsshowthephysicalconfigurationsofsoftwareandhardware. Thefollowingdeploymentdiagramshowstherelationshipsamongsoftwareandhardware componentsinvolvedinrealestatetransactions.

edn.embarcadero.com/print/31863

9/10

1/9/13

Practical UML: A HandsOn Introduction for Developers

Thephysicalhardwareismadeupof nodes.Eachcomponentbelongsonanode.Componentsare shownasrectangleswithtwotabsattheupperleft.

UMLToolsandModelingTools CreatingandmodifyingUMLdiagramscanbelaborandtimeintensive.TheUMLmodelingtools fromEmbarcaderoTechnologiesmakeiteasytocreatediagramsliketheonesinthisarticleplus theyprovideagreatamountofotherfunctionalityincludingmodelandcodesynchronization. EmbarcaderoDelphiisthefastestwaytobuildnativeWindowsapplications.TheProfessional editionincludesUMLcodevisualization.TheEnterpriseeditionincludesmodelingwithtwoway synchronizationbetweenmodelandcode.TheArchitecteditionincludestheabilitytocreate languageneutralUMLmodelingprojects.LearnmoreaboutDelphiordownloadatrialedition ofDelphiandtryitforyourself. SimilarUMLmodelingfunctionalityisavailableforC++inC++Builder,forJavainJBuilderandfor WindowsinEmbarcaderoRADStudio.Databasemodelingandbusinessmodelingareavailablein EmbarcaderoER/StudioandER/StudioBusinessArchitect. Forthelatestuptodatetechniquesinthe UnifiedModelingLanguageand AgileSoftware DevelopmentProcesses,andforallofthelatestinformationonhowtodeliver bettersoftware faster,visitTheEmbarcaderoDeveloperNetwork

Copyright2003BorlandSoftwareCorporation,Inc.Allrightsreserved.AllBorlandandBorland brandsandproductnamesaretrademarksorregisteredtrademarksofBorland.Youmaynotuse anyoftheBorlandtrademarkswithoutBorland'spriorwrittenpermission.Allotherbrandand productnamesmaybetrademarksorregisteredtrademarksoftheirrespectiveholders.


Publishedon:12/4/200312:00:00AM
ServerResponsefrom:ETNASC01

Copyright19942012EmbarcaderoTechnologies,Inc.Allrightsreserved.

edn.embarcadero.com/print/31863

10/10

Вам также может понравиться