Object Modeling with OMG UML Tutorial Series Behavioral Modeling Gunnar Övergaard, Bran Selic, Conrad Bock and Morgan Björkander UML Revision Task Force © 1999-2001 OMG and Contributors: Crossmeta, EDS, IBM, Enea Data, Hewlett-Packard, IntelliCorp, Kabira Technologies, Klasse Objecten, Rational Software, Telelogic, Unisys 1 Overview ! ! ! Tutorial series UML Quick Tour Behavioral Modeling ! Part 1: Interactions and Collaborations ! ! Part 2: Statecharts ! ! ! Gunnar Övergaard, Jaczone AB Bran Selic, Rational Software Morgan Björkander, Telelogic Part 3: Activity Graphs ! Conrad Bock, Kabira Technologies Behavioral Modeling with UML 2 Tutorial Series ! ! ! Lecture 1: Introduction to UML: Structural and Use Case Modeling Lecture 2: Behavioral Modeling with UML Lecture 3: Advanced Modeling with UML [Note: This version of the tutorial series is based on OMG UML Specification v. 1.4, UML Revision Task Force recommended final draft, OMG doc# ad/01-02-13.] Behavioral Modeling with UML 3 Tutorial Goals ! What you will learn: ! ! ! ! ! ! what the UML is and what is it not UML’s basic constructs, rules and diagram techniques how the UML can model large, complex systems how the UML can specify systems in an implementation-independent manner how UML, XMI and MOF can facilitate metadata integration What you will not learn: ! ! ! Object Modeling Development Methods or Processes Metamodeling Behavioral Modeling with UML 4 Quick Tour ! The UML is a graphical language for ! ! ! ! ! ! ! ! specifying visualizing constructing documenting the artifacts of software systems Added to the list of OMG adopted technologies in November 1997 as UML 1.1 Most recent minor revision is UML 1.3, adopted in November 1999 Next minor revision will be UML 1.4, planned to be adopted in Q2 2001 Next major revision will be UML 2.0, planned to be completed in 2002 Behavioral Modeling with UML 5 UML Goals ! ! ! ! ! ! ! Define an easy-to-learn but semantically rich visual modeling language Unify the Booch, OMT, and Objectory modeling languages Include ideas from other modeling languages Incorporate industry best practices Address contemporary software development issues ! scale, distribution, concurrency, executability, etc. Provide flexibility for applying different processes Enable model interchange and define repository interfaces Behavioral Modeling with UML 6 OMG UML Evolution 2001 (planned major revision) <<document>> UML 2.0 <<refine>> Q3 2000 (planned minor revision) <<document>> UML 1.4 <<refine>> Q3 1999 <<document>> UML 1.3 Other relevant standards TBA <<informalLiaison>> ISO Publicly Available Specifications (PAS) <<formalLiaison>> <<refine>> Q2 1998 <<document>> UML 1.2 Editorial revision with no significant technical changes. <<refine>> Q3 1997 (OMG Adopted Technology) <<document>> UML 1.1 Unification of major modeling languages, including Booch, OMT and Objectory Behavioral Modeling with UML 7 OMG UML 1.3 Specification ! ! ! ! UML UML UML UML ! ! ! ! ! Summary Semantics Notation Guide Standard Profiles Software Development Processes Business Modeling UML CORBAfacility Interface Definition UML XML Metadata Interchange DTD Object Constraint Language Behavioral Modeling with UML 8 Tutorial Focus: the Language ! language = syntax + semantics ! ! ! ! syntax = language elements (e.g. words) are assembled into expressions (e.g. phrases, clauses) semantics = the meanings of the syntactic expressions UML Notation Guide – defines UML’s graphic syntax UML Semantics – defines UML’s semantics Behavioral Modeling with UML 9 Unifying Concepts ! classifier-instance dichotomy ! ! specification-realization dichotomy ! ! e.g. an object is an instance of a class OR a class is the classifier of an object e.g. an interface is a specification of a class OR a class is a realization of an interface analysis-time vs. design-time vs. runtime ! ! modeling phases (“process creep”) usage guidelines suggested, not enforced Behavioral Modeling with UML 10 Language Architecture ! ! Metamodel architecture Package structure Behavioral Modeling with UML 11 Metamodel Architecture <<metamodel>> MOF Metametamodel Meta-Metamodel Layer (M3): Specifies metametaclasses for the UML metamodel <<metamodel>> UML Metamodel Metamodel Layer (M2): Specifies metaclasses for the UML metamodel, such as Class Model Layer (M1): Specifies classes for the UML user models, such as Passenger, Ticket, TravelAgency User Model :Foo :Bar :Baz Behavioral Modeling with UML User Objects Layer (M0): User objects that are instances of UML user model classes, such as instances of Passenger, Ticket, TravelAgency 12 Package Structure <<metamodel>> UML Behavioral Elements Model Management dependency Foundation Behavioral Modeling with UML package 13 Package Structure Behavioral Elements Collaborations Use Cases State Machines Activity Graphs Model Management Common Behavior Foundation Behavioral Modeling with UML 14 Behavioral Modeling ! ! ! Part 1: Interactions and Collaborations Part 2: Statecharts Part 3: Activity Diagrams Behavioral Modeling with UML 15 Interactions ! ! ! ! ! ! What are interactions? Core concepts Diagram tour When to model interactions Modeling tips Example: A Booking System Behavioral Modeling with UML 16 What are interactions? ! ! Interaction: a collection of communications between instances, including all ways to affect instances, like operation invocation, as well as creation and destruction of instances The communications are partially ordered (in time) Behavioral Modeling with UML 17 Interactions: Core Elements Construct Description Instance (object, data value, component instance etc.) An entity with a unique identity and to which a set of operations can be applied (signals be sent) and which has a state that stores the effects of the operations (the signals). Action A specification of an executable statement. A few different kinds of actions are predefined, e.g. CreateAction, CallAction, DestroyAction, and UninterpretedAction. Behavioral Modeling with UML Syntax name attr values textual 18 Interaction: Core Elements Construct Description Stimulus A communication between two instances. Operation A declaration of a service that can be requested from an instance to effect behavior. Signal A specification of an asynchronous stimulus communicated between instances. Behavioral Modeling with UML (cont’d) Syntax textual «Signal» Name parameters 19 Interaction: Core Relationships Construct Link Description Syntax A connection between instances. Attribute Link A named slot in an instance, which holds the value of an attribute. Behavioral Modeling with UML textual 20 Example: Instance triangle : Polygon underlined name triangle : Polygon center : Point = (2,2) vertices : Point* = ((0,0), (4, 0), (2,4)) borderColor : Color = black fillColor : Color = white attribute links triangle : Polygon Behavioral Modeling with UML 21 Example: Instances and Links : Family Joe : Person husband wife Behavioral Modeling with UML Jill : Person 22 Operation and Method Triangle + move (in dist : Point) + scale (in factor : Real) foreach v in vertices do v.x := v.x + dist.x; v.y := v.y + dist.y foreach v in vertices do v.x := factor * v.x; v.y := factor * v.y Behavioral Modeling with UML 23 Interaction Diagram Tour ! Show interactions between instances in the model ! ! ! ! graph of instances (possibly including links) and stimuli existing instances creation and deletion of instances Kinds ! ! sequence diagram (temporal focus) collaboration diagram (structural focus) Behavioral Modeling with UML 24 Interaction Diagrams Sequence Diagram x y Collaboration Diagram z 1.1: a 1.2: c x a y b 1.1.1: b c z Behavioral Modeling with UML 25 Sequence Diagram object symbol name : Class other lifeline stimulus name (…) activation new (…) : Class delete return create Behavioral Modeling with UML 26 Arrow Label predecessor sequence-expression return-value := message-name argument-list move (5, 7) 3.7.4: move (5, 7) A3, B4 / C3.1: res := getLocation (fig) 3.7 *[1..5]: move (5, 7) predecessor sequence number return value iteration message name 3.7 [ z > 0 ]: move (5, 7) Behavioral Modeling with UML argument list condition 27 Different Kinds of Arrows Procedure call or other kind of nested flow of control UML 1.4: Asynchronous Flat flow of control Explicit asynchronous flow of control UML 1.4: Variant of async Return Behavioral Modeling with UML 28 Example: Different Arrows UML 1.4: Alternative notation UML 1.4: Asynchronous flow for async flow Nested Flow teller : Order : Article Flat Flow caller exchange Asynchronous Flow callee appl err handl alarm lift receiver getValue unknown dial tone price alarm dial digit dial digit getName ringing tone ringing signal lift receiver Behavioral Modeling with UML 29 Recursion, Condition, etc. calculator filter value [ x > 0]: getValue () [ x < 0]: transform () getValue () iterate () Behavioral Modeling with UML 30 Collaboration Diagram object symbol standard stereotype link symbol redisplay () stimulus window : Controller standard stereotype 1: displayPositions (window) 1.1 *[i := 1..n]: drawSegment (i) standard stereotype 1.1.1a: r0 := position () left : Bead window «parameter» standard constraint 1.1.3.1 add (self) wire contents {new} «local» line wire :Wire «self» : Window 1.1.2: create (r0, r1) 1.1.3: display (window) 1.1.1b: r1 := position () {new} : Line standard constraint right : Bead Behavioral Modeling with UML 31 When to Model Interactions ! ! ! To specify how the instances are to interact with each other. To identify the interfaces of the classifiers. To distribute the requirements. Behavioral Modeling with UML 32 Interaction Modeling Tips ! ! ! ! ! Set the context for the interaction. Include only those features of the instances that are relevant. Express the flow from left to right and from top to bottom. Put active instances to the left/top and passive ones to the right/bottom. Use sequence diagrams ! ! ! to show the explicit ordering between the stimuli when modeling real-time Use collaboration diagrams ! ! when structure is important to concentrate on the effects on the instances Behavioral Modeling with UML 33 Example: A Booking System Behavioral Modeling with UML 34 Use Case Description: Change Flt Itinerary ! ! ! Actors: traveler, client account db, airline reservation system Preconditions: Traveler has logged in Basic course: ! ! ! ! ! ! ! ! Traveler selects ‘change flight itinerary’ option System retrieves traveler’s account and flight itinerary from client account database System asks traveler to select itinerary segment she wants to change; traveler selects itinerary segment. System asks traveler for new departure and destination information; traveler provides information. If flights are available then … … System displays transaction summary. Alternative course: ! If no flights are available then… Behavioral Modeling with UML 35 Sequence Diagram: Change Flight Itinerary Traveler : Booking System Client Account DBMS Airline Reservation System change flight itinerary get customer account get itinerary present itinerary select segment present detailed info update information available flight : : Behavioral Modeling with UML 36 Collaboration Diagram: Change Flt Itinerary 1: change flight itinerary 5: select segment 7: update information 2: get customer account 3: get itinerary : Booking System 4: present itinerary Traveler 6: present detailed info Client Account DBMS 8: available flight Airline Reservation System Behavioral Modeling with UML 37 Collaboration ! ! ! ! ! ! What is a collaboration? Core concepts Diagram tour When to model collaborations Modeling tips Example: A Booking System Behavioral Modeling with UML 38 What is a collaboration? ! ! Collaboration: a collaboration defines the roles a set of instances play when performing a particular task, like an operation or a use case. Interaction:an interaction specifies a communication pattern to be performed by instances playing the roles of a collaboration. Behavioral Modeling with UML 39 Collaborations: Core Elements Construct Collaboration Interaction Description A collaboration describes how an operation or a classifier, like a use case, is realized by a set of classifiers and associations used in a specific way. The collaboration defines a set of roles to be played by instances and links, possibly including a collection of interactions. Syntax Name An interaction describes a communication pattern between instances when they play the roles of the collaboration. Behavioral Modeling with UML 40 Collaborations: Core Elements Construct Description Collaboration- A collection of instances which together play the roles declared Instance in a collaboration. InteractionInstance (cont’d) Syntax Name A collection of stimuli exchanged between instances playing specific roles according to the communication pattern of an interaction. All new in UML 1.4 Behavioral Modeling with UML 41 Collaborations: Core Elements Construct Description Classifier Role A classifier role is a specific role played by a participant in a collaboration. It specifies a restricted view of a classifier, defined by what is required in the collaboration. Message A message specifies one communication between instances. It is a part of the communication pattern given by an interaction. Behavioral Modeling with UML (cont’d) Syntax / Name label 42 Collaborations: Core Relationships Construct Description Association Role An association role is a specific usage of an association needed in a collaboration. Generalization A generalization is a taxonomic relationship between a more general element and a more specific element. The more specific element is fully consistent with the more general element. Behavioral Modeling with UML Syntax 43 Classifier-Instance-Role Trichotomy ! ! ! An Instance is an entity with behavior and a state, and has a unqiue identity. A Classifier is a description of an Instance. A Classifier Role defines a usage (an abstraction) of an Instance. id «originates from» ClassName «conforms to» / RoleName Behavioral Modeling with UML «view of» 44 Classifier-Instance-Role Trichotomy (cont’d) Classifier Attribute-1 Attribute-2 Attribute-3 Operation-1 (…) Operation-2 (…) Operation-3 (…) ClassifierRole Attribute-1 Attribute-2 «originates from» «conforms to» Operation-1 (…) Operation-3 (…) Instance AttributeValue-1 AttributeValue-2 AttributeValue-3 •The attribute values of an Instance corresponds to the attributes of its Classifier. •All attributes required by the ClassifierRole have corresponding attribute values in the Instance. •All operations defined in the Instance’s Classifier can be applied to the Instance. •All operations required by the ClassifierRole are applicable to the Instance. Behavioral Modeling with UML 45 Different Ways to Name a Role / ClassifierRoleName : ClassifierName A role name is preceeded by a ‘/’ Example: A classifier name is preceeded by a ‘:’ / Parent : Person / Parent : Person instanceName / ClassifierRoleName : ClassifierName Example: : Person Charlie Charlie / Parent Charlie : Person Charlie / Parent : Person Behavioral Modeling with UML 46 Association and Association Role Class Class-1 Association Class 0..5 {changeable} Class-2 «view of» «view of» / Role-1 {frozen} ClassifierRole «view of» 3..4 / Role-2 AssociationRole ClassifierRole •An Association Role specifies the required properties of a Link used in a Collaboration. •The properties of an AssociationEnd may be restricted by a AssociationEndRole. Behavioral Modeling with UML 47 Example: A School / Teacher : Person 1 tutor student * / Student : Person program : Text position : Text faculty member * faculty 1 1 lecturer participant * given course * : Faculty taken course * : Course Behavioral Modeling with UML 48 Role Model vs. Class Model The Classes give the complete description while the Roles specify one usage. Role Model Class Model Extra attribute / Teacher : Person 1 position : Text * 1 : Faculty * / Student : Person Person Resulting multiplicity program : Text * * 1 * * : Course 0..1 Faculty Behavioral Modeling with UML Resulting multiplicity 0..1 name : Text position : Text program : Text 1 * * * * Course 49 A Collaboration and Its Roles A Collaboration and how its roles are mapped onto a collection of Classifiers and Associations. CollaborationName roleName-1 roleName-2 Classifier-1 Behavioral Modeling with UML roleName-3 Classifier-2 50 Patterns in UML Constraint that must be fulfilled in each instance of this pattern. Handler.reading = length (Subject.queue) Handler.range = {0..Subject.capacity} Observer Subject Handler CallQueue SlidingBarIcon queue : List of Call source : Object waitAlarm : Alarm capacity : Integer reading : Real color : Color range : Interval Behavioral Modeling with UML 51 Generalization Between Collaborations Subject CallQueue Handler Subject ManagedQueue SlidingBarIcon Observer Supervisor Manager Controller •All roles defined in the parent are present in the child. •Some of the parent’s roles may be overridden in the child. •An overridden role is usually the parent of the new role. Behavioral Modeling with UML 52 Collaboration Diagram Tour ! ! Show Classifier Roles and Association Roles, possibly together with extra constraining elements Kinds ! ! ! Instance level – Instances and Links Specification level – Roles Static Diagrams are used for showing Collaborations explicitly Behavioral Modeling with UML 53 Collaboration Diagram at Specification Level / Teacher : Person 1 tutor position : Text faculty member * faculty 1 : Faculty student * / Student : Person program : Text * participant 1 lecturer given course * * taken course : Course UML 1.4: The diagram shows the contents of a Collaboration Behavioral Modeling with UML 54 Collaboration Diagram at Instance Level student tutor faculty member Alice / Student John / Teacher tutor faculty student participant Bob / Student participant : Faculty taken course faculty Sara / Teacher lecturer given course taken course English : Course faculty member UML 1.4: The diagram shows the contents of a CollaborationInstance Behavioral Modeling with UML 55 Collaborations including Interactions Sequence Diagram x y Collaboration Diagram z 1.1: a 1.2: c x a y b 1.1.1: b c z UML 1.4: The diagrams show the contents of a CollaborationInstance with an InteractionInstance superposed Behavioral Modeling with UML 56 Roles on Sequence Diagrams Sequence Diagram /X /Y /Z a b c UML 1.4: The diagram shows the contents of a Collaboration with an Interaction superposed Behavioral Modeling with UML 57 Collaboration Diagram with Constraining Elements / Generator : Printer Device Constraining Element (A Generalization is not an AssociationRole ) : Laser Printer : Line Printer Behavioral Modeling with UML 58 Static Diagram With Collaboration and Classifiers Subject CallQueue Handler Subject ManagedQueue SlidingBarIcon Observer Supervisor Manager Behavioral Modeling with UML Controller 59 When to Model Collaborations ! ! ! Use Collaborations as a tool to find the Classifiers. Trace a Use Case / Operation onto Classifiers. Map the specification of a Subsystem onto its realization (Tutorial 3). Behavioral Modeling with UML 60 Collaboration Modeling Tips ! ! ! A collaboration should consist of both structure and behavior relevant for the task. A role is an abstraction of an instance, it is not a class. Look for ! ! ! initiators (external) handlers (active) managed entities (passive) Behavioral Modeling with UML 61 Example: A Booking System Behavioral Modeling with UML 62 Use Case Description: Change Flt Itinerary ! ! ! Actors: traveler, client account db, airline reservation system Preconditions: Traveler has logged in Basic course: ! ! ! ! ! ! ! ! Traveler selects ‘change flight itinerary’ option System retrieves traveler’s account and flight itinerary from client account database System asks traveler to select itinerary segment she wants to change; traveler selects itinerary segment. System asks traveler for new departure and destination information; traveler provides information. If flights are available then … … System displays transaction summary. Alternative course: ! If no flights are available then… Behavioral Modeling with UML 63 Booking System: Change Flt Itinerary Collaboration 4: get customer account 7: get itinerary 1: change flight itinerary : Traveler / Flight Itenerary Form 10: present 2: create modifier / DBMS Protocol 9: display / Flight Itinerary Modifier 5: create / Account : Client Account DBMS 3: get customer account 6: get itinerary 8: create / Itinerary / ARS Protocol : Airline Reservation System Behavioral Modeling with UML 64 Wrap Up: Interactions & Collaborations ! ! Instances, Links and Stimuli are used for expressing the dynamics in a model. Collaboration is a tool for ! ! ! ! identification of classifiers specification of the usage of instances expressing a mapping between different levels of abstraction Different kinds of diagrams focus on time or on structure Behavioral Modeling with UML 65 Behavioral Modeling ! ! ! Part 1: Interactions and Collaborations Part 2: Statecharts Part 3: Activity Diagrams Behavioral Modeling with UML 66 Overview ! ! ! ! ! Basic State Machine Concepts Statecharts and Objects Advanced Modeling Concepts Case Study Wrap Up Behavioral Modeling with UML 67 Automata ! ! A machine whose output behavior is not only a direct consequence of the current input, but of some past history of its inputs Characterized by an internal state which represents this past experience ON ON ON ON OFF OFF Behavioral Modeling with UML 68 State Machine (Automaton) Diagram ! Graphical rendering of automata behavior on Lamp On on off off Lamp Off Behavioral Modeling with UML 69 Outputs and Actions ! As the automaton changes state it can generate outputs: on on Lamp On print(”on”) Lamp On on on/print(”on”) off off Lamp Off off Mealy automaton Lamp Off off Moore automaton Behavioral Modeling with UML 70 Extended State Machines ! Addition of variables (“extended state”) on ctr ctr :: Integer Integer Lamp On on/ctr := ctr + 1 off off Lamp Off Behavioral Modeling with UML 71 A Bit of Theory ! An extended (Mealy) state machine is defined by: ! ! ! ! a a a a set set set set ! ! ! ! ! of of of of input signals (input alphabet) output signals (output alphabet) states transitions triggering signal action a set of extended state variables an initial state designation a set of final states (if terminating automaton) Behavioral Modeling with UML 72 Basic UML Statechart Diagram “top” “top” state state Initial Initial pseudostate pseudostate State State top Trigger Trigger Ready Transition Transition stop /ctr := 0 Final Final state state Done Action Action stop Behavioral Modeling with UML 73 What Kind of Behavior? ! In general, state machines are suitable for describing event-driven, discrete behavior ! inappropriate for modeling continuous behavior threshold time Behavioral Modeling with UML 74 Event-Driven Behavior ! Event = a type of observable occurrence ! interactions: ! ! ! occurrence of time instants (time event) ! ! ! ! synchronous object operation invocation (call event) asynchronous signal reception (signal event) interval expiry calendar/clock time change in value of some entity (change event) Event Instance = an instance of an event (type) ! occurs at a particular time instant and has no duration Behavioral Modeling with UML 75 The Behavior of What? ! In principle, anything that manifests event-driven behavior ! ! In practice: ! ! ! NB: there is no support currently in UML for modeling continuous behavior the behavior of individual objects object interactions The dynamic semantics of UML state machines are currently mainly specified for the case of active objects Behavioral Modeling with UML 76 Basic State Machine Concepts Statecharts and Objects Advanced Modeling Concepts Case Study Wrap Up Behavioral Modeling with UML 77 Object Behavior - General Model ! Simple server model: Handling Handling depends depends on on specific specific request request type type Initialize Initialize Object Object Wait Waitfor for Request Request void:offHook (); {busy = true; obj.reqDialtone(); … }; Handle Handle Request Request Terminate Terminate Object Object Behavioral Modeling with UML 78 Object Behavior and State Machines ! Direct mapping: on Initialize Object Lamp On Wait for Event Handle Event on/print(”on”) off Lamp Off Terminate Object off stop Behavioral Modeling with UML 79 Object and Threads •Passive objects: depend on external power (thread of execution) •Active objects: self-powered (own thread of execution) Initialize Initialize Object Object Initialize Initialize Object Object Wait Waitfor for Request Request Wait Waitfor for Request Request Handle Handle Request Request Handle Handle Request Request Terminate Terminate Object Object Terminate Terminate Object Object Behavioral Modeling with UML 80 Passive Objects: Dynamic Semantics Initialize Initialize Object Object Wait Waitfor for Request Request Handle Handle Request Request Terminate Terminate Object Object •Encapsulation does not protect the object from concurrency conflicts! •Explicit synchronization is still required Behavioral Modeling with UML 81 Active Objects and State Machines ! Objects that encapsulate own thread of execution anActiveObject #currentEvent : Eventpoll/defer created start + start ( ) + poll ( ) + stop ( ) start/^master.ready() ready ready stop/ poll/^master.ack() Behavioral Modeling with UML 82 Active Objects: Dynamic Semantics ActiveObject: Run-to-completion model: •serialized event handling •eliminates internal concurrency •minimal context switching overhead Behavioral Modeling with UML 83 The Run-to-Completion Model ! A high priority event for (another) active object will preempt an active object that is handling a low-priority event Active1 Active1 Active2 Active2 lo hi hi Behavioral Modeling with UML 84 Basic State Machine Concepts Statecharts and Objects Advanced Modeling Concepts Case Study Wrap Up Behavioral Modeling with UML 85 State Entry and Exit Actions ! A dynamic assertion mechanism LampOn entry/lamp.on(); e2 exit/lamp.off(); e1 Behavioral Modeling with UML 86 Order of Actions: Simple Case ! ! Exit actions prefix transition actions Entry action postfix transition actions LampOn entry/lamp.on(); LampOff off/printf(“to off”); entry/lamp.off(); exit/printf(“exiting”); exit/printf(“exiting”); Resulting action sequence: printf (“exiting”); printf(“exiting”); printf (“to off”); printf(“to lamp.off(); off/printf(“needless”); printf (“exiting”); printf(“exiting”); printf (“needless”); printf(“needless”); lamp.off(); Behavioral Modeling with UML 87 Internal Transitions ! Self-transitions that bypass entry and exit actions Internal transition triggered by an “off” event LampOff entry/lamp.off(); exit/printf(“exiting”); off/null; Behavioral Modeling with UML 88 State (“Do”) Activities ! Forks a concurrent thread that executes until: ! ! the action completes or the state is exited through an outgoing transition “do” activity Error entry/printf(“error!”) do/while (true) alarm.ring(); Behavioral Modeling with UML 89 Guards ! Conditional execution of transitions ! guards (Boolean predicates) must be side-effect free bid [value < 100] /reject bid [value >= 200] /sell Selling Happy bid [(value >= 100) & (value < 200)] /sell Unhappy Behavioral Modeling with UML 90 Static Conditional Branching ! Merely a graphical shortcut for convenient rendering of decision trees Selling Happy bid [value >= 200] /sell [value < 100] /reject [(value >= 100) & (value < 200)] /sell Unhappy Behavioral Modeling with UML 91 Dynamic Conditional Branching ! Choice pseudostate: guards are evaluated at the instant when the decision point is reached Selling Happy bid /gain := calculatePotentialGain(value) [gain >= 200] /sell [gain < 100] /reject [(gain >= 100) & (gain < 200)] /sell Dynamic Dynamic choicepoint choicepoint Unhappy Behavioral Modeling with UML 92 Hierarchical State Machines ! Graduated attack on complexity ! states decomposed into state machines LampOff LampOff entry/lamp.off() flash/ LampFlashing FlashOn FlashOn entry/lamp.on() off/ 1sec/ on/ LampOn LampOn 1sec/ on/ on/ FlashOff FlashOff entry/lamp.off() entry/lamp.on() Behavioral Modeling with UML 93 “Stub” Notation ! Notational shortcut: no semantic significance LampOff LampOff entry/lamp.off() flash/ LampFlashing FlashOn off/ on/ LampOn LampOn on/ on/ FlashOff entry/lamp.on() Behavioral Modeling with UML 94 Group Transitions ! Default Default transition transition to to Higher-level transitions the the initial initial pseudostate pseudostate LampOff LampOff entry/lamp.off() LampFlashing flash/ FlashOn FlashOn entry/lamp.on() off/ 1sec/ 1sec/ on/ LampOn LampOn on/ FlashOff FlashOff entry/lamp.off() entry/lamp.on() Group Group transition transition Behavioral Modeling with UML 95 Completion Transitions ! Triggered by a completion event ! generated automatically when an immediately nested state machine terminates Committing completion transition (no trigger) Phase1 Phase1 CommitDone Phase2 Phase2 Behavioral Modeling with UML 96 Triggering Rules ! Two or more transitions may have the same event trigger ! ! innermost transition takes precedence event is discarded whether or not it triggers a transition LampFlashing FlashOn FlashOn on/ on/ off/ FlashOff FlashOff Behavioral Modeling with UML 97 Deferred Events ! Events can be retained if they do not trigger a transition LampOff LampOff Deferred Deferred event event entry/lamp.off() off/defer off/ on/ LampOn LampOn entry/lamp.on() Behavioral Modeling with UML 98 Order of Actions: Complex Case ! Same approach as for the simple case S1 exit/exS1 S2 entry/enS2 initS2 S11 exit/exS11 E/actE S21 entry/enS21 Actions execution sequence: exS11 " exS1 " actE " enS2 " initS2 " enS21 Behavioral Modeling with UML 99 History ! Return to a previously visited hierarchical state ! deep and shallow history options Diagnosing suspend/ resume/ H* H* Diagnostic1 Diagnostic1 Diagnostic2 Diagnostic2 Step11 Step11 Step21 Step21 Step12 Step12 Step22 Step22 Behavioral Modeling with UML 100 Orthogonality ! age Multiple simultaneous perspectives on the same entity financialStatus Child Poor Adult Rich Retiree Behavioral Modeling with UML 101 Orthogonal Regions ! Combine multiple simultaneous descriptions age financialStatus Child Poor Adult Retiree age financialStatus Rich Child Poor Adult Retiree Rich Behavioral Modeling with UML 102 Orthogonal Regions - Semantics ! All mutually orthogonal regions detect the same events and respond to them “simultaneously” ! usually reduces to interleaving of some kind legalStatus LawAbiding LawAbiding robBank/ Outlaw Outlaw financialStatus Poor Poor robBank/ Rich Rich Behavioral Modeling with UML 103 Interactions Between Regions ! Typically through shared variables or awareness of other regions’ state changes sane sane :: Boolean Boolean flying flying :: Boolean Boolean Catch22 Catch22 sanityStatus flightStatus Crazy Crazy Flying Flying entry/sane entry/sane := := false; false; entry/flying entry/flying := := true; true; (flying)/ request Grounding/ (sane)/ (~sane)/ Sane Sane Grounded Grounded entry/sane entry/sane := := true; true; entry/flying entry/flying := := false; false; Behavioral Modeling with UML 104 Transition Forks and Joins ! For transitions into/out of orthogonal regions: age Child Child Staff Staff Member Member Adult Adult Retiree Retiree Manager Manager employee Behavioral Modeling with UML 105 Common Misuse of Orthogonality ! Using regions to model independent objects Person1 Person2 Person1 Person2 Child Child Adult Adult Retiree Retiree Behavioral Modeling with UML 106 Basic State Machine Concepts Statecharts and Objects Advanced Modeling Concepts Case Study Wrap Up Behavioral Modeling with UML 107 Case Study: Protocol Handler ! A multi-line packet switch that uses the alternating-bit protocol as its link protocol AB AB protocol protocol End user AB sender line card 1 End user . . . unreliable telecom lines AB sender AB receiver End user AB receiver SWITCH line card N Behavioral Modeling with UML 108 Alternating Bit Protocol (1) ! A simple one-way point-to-point packet protocol AB AB protocol protocol packetizer Sender Receiver unpacker data(1) pktA data(1) ack ackA ack data(2) pktB data(2) ack ackB ack …etc. Behavioral Modeling with UML 109 Alternating Bit Protocol (2) ! State machine specification Receiver SM Sender SM AcceptPktA RcvdPktA ackB/^ack data/^pktA pktA/^data ack/^ackA timeout/^pktB WaitAckA timeout/^ackB WaitAckB WaitPktA timeout/^ackA timeout/^pktA ackA/^ack WaitPktB data/^pktB pktB/^data AcceptPktB ack/^ackB RcvdPktB Behavioral Modeling with UML 110 Additional Considerations ! Support (control) infrastructure operator interface AB receiver System operator AB lines manager AB sender SWITCH DB interface DBase Behavioral Modeling with UML 111 Control The set of (additional) mechanisms and actions required to bring a system into the desired operational state and to maintain it in that state in the face of various planned and unplanned disruptions For software systems this includes: •system/component start-up and shut-down •failure detection/reporting/recovery •system administration, maintenance, and provisioning •(on-line) software upgrade Behavioral Modeling with UML 112 Retrofitting Control Behavior Hardware Audit JustCreated Analysing Failure ReadyToGo GettingData AcceptPktA WaitAckA Failed WaitAckB AcceptPktB Behavioral Modeling with UML 113 The Control Automaton ! In isolation, the same control behavior appears much simpler JustCreated GettingData Hardware Audit ReadyToGo Analysing Failure Failed Operational Behavioral Modeling with UML 114 Exploiting Inheritance ! Abstract control classes can capture the common control behavior AbstractController Sender Receiver . . . Behavioral Modeling with UML 115 Exploiting Hierarchical States JustCreated Analysing Failure AbstractController GettingData Failed Hardware Audit ReadyToGo Sender Operational Behavioral Modeling with UML 116 Basic State Machine Concepts Statecharts and Objects Advanced Modeling Concepts Case Study Wrap Up Behavioral Modeling with UML 117 Wrap Up: Statecharts ! UML uses an object-oriented variant of Harel’s statecharts ! ! Used to model event-driven (reactive) behavior ! ! adjusted to software modeling needs well-suited to the server model inherent in the object paradigm Primary use for modeling the behavior of active event-driven objects ! ! systems modeled as networks of collaborating state machines run-to-completion paradigm significantly simplifies concurrency management Behavioral Modeling with UML 118 Wrap Up: Statecharts (cont’d) ! Includes a number of sophisticated features that realize common state-machine usage patterns: ! ! ! ! entry/exit actions state activities dynamic and static conditional branching Also, provides hierarchical modeling for dealing with very complex systems ! ! ! hierarchical states hierarchical transitions orthogonality Behavioral Modeling with UML 119 Behavioral Modeling ! ! ! Part 1: Interactions and Collaborations Part 2: Statecharts Part 3: Activity Diagrams Behavioral Modeling with UML 120 Activity Diagram Applications ! ! ! ! Intended for applications that need control flow or object/data flow models … ... rather than event-driven models like state machines. For example: business process modeling and workflow. The difference in the three models is how step in a process is initiated, especially with respect to how the step gets its inputs. Behavioral Modeling with UML 121 Control Flow ! ! ! Each step is taken when the previous one finishes … …regardless of whether inputs are available, accurate, or complete (“pull”). Emphasis is on order in which steps are taken. Weather Info Start Analyze AnalyzeWeather WeatherInfo Info Not UML Notation! Chart ChartCourse Course Cancel CancelTrip Trip Behavioral Modeling with UML 122 Object/Data Flow ! ! ! Each step is taken when all the required input objects/data are available … … and only when all the inputs are available (“push”). Emphasis is on objects flowing between steps. Design DesignProduct Product Acquire AcquireCapital Capital Procure Procure Materials Materials Build Build Subassembly Subassembly22 Build Build Subassembly Subassembly11 Not UML Notation Final Final Assembly Assembly Behavioral Modeling with UML 123 State Machine ! ! ! Each step is taken when events are detected by the machine … … using inputs given by the event. Emphasis is on reacting to environment. Ready ReadyTo ToStart Start Coin Deposited Ready ReadyFor ForOrder Order Selection Made Cancel Button Pressed Dispense Dispense Product Product Return Return Change Change Not UML Notation Behavioral Modeling with UML 124 Activity Diagrams Based on State Machines ! ! ! ! Currently activity graphs are modeled as a kind of state machine. Modeler doesn't normally need to be aware of this sleight-of-hand ... ... but will notice that "state" is used in the element names. Activity graphs will become independent of state machines in UML 2.0. Behavioral Modeling with UML 125 Kinds of Steps in Activity Diagrams ! Action (State) ! Subactivity (State) ! ! ! Action Subactivity Just like their state machine counterparts (simple state and submachine state) except that ... ... transitions coming out of them are taken when the step is finished, rather than being triggered by a external event, ... ... and they support dynamic concurrency. Behavioral Modeling with UML 126 Action (State) Action ! ! An action is used for anything that does not directly start another activity graph, like invoking an operation on an object, or running a user-specified action. However, an action can invoke an operation that has another activity graph as a method (possible polymorphism). Behavioral Modeling with UML 127 Subactivity (State) Subactivity ! ! ! A subactivity (state) starts another activity graph without using an operation. Used for functional decomposition, nonpolymorphic applications, like many workflow systems. The invoked activity graph can be used by many subactivity states. Behavioral Modeling with UML 128 Example POEmployee.sortMail Deliver Mail Deliver Mail POEmployee sortMail() Check Out Truck Behavioral Modeling with UML Put Mail In Boxes 129 Activity Graph as Method POEmployee.sortMail POEmployee.deliverMail POEmployee PO Employee Deliver Mail Method sortMail() deliverMail() ! ! «realize» Check Out Truck Put Mail In Boxes Application is completely OO when all action states invoke operations All activity graphs are methods for operations. Behavioral Modeling with UML 130 Dynamic concurrency Action/Subactivity ! Applies to actions and subactivities. ! Not inherited from state machines. ! ! ! ! * Invokes an action or subactivity any number of times in parallel, as determined by an expression evaluated at runtime. Expression also determines arguments. Upper right-hand corner shows a multiplicity restricting the number of parallel invocations. Outgoing transition triggered when all invocations are done. Currently no standard notation for concurrency expression or how arguments are accessed by actions. Attach a note as workaround for expression. Issue for UML 2.0. Behavioral Modeling with UML 131 Object Flow (State) Class [State] ! ! ! A special sort of step (state) that represents the availability of a particular kind of object, perhaps in a particular state. No action or subactivity is invoked and control passes immediately to the next step (state). Places constraints on input and output parameters of steps before and after it. Behavioral Modeling with UML 132 Object Flow (State) Take Order ! ! ! Order [Taken] Fill Order Take Order must have an output parameter giving an order, or one of its subtypes. Fill Order must have an input parameter taking an order, or one of its supertypes. Dashed lines used with object flow have the same semantics as any other state transition. Behavioral Modeling with UML 133 Coordinating Steps ! Inherited from state machines ! Initial state ! Final state ! Fork and join Behavioral Modeling with UML 134 Coordinating Steps ! ! Decision point and merge ( ) are inherited from state machines. For modeling conventional flow chart decisions. Calculate Cost [cost < $50] Charge Account [cost >= $50] Get Authorization Behavioral Modeling with UML 135 Coordinating Steps ! ! State machine notation Synch state ( ) is inherited from state machines but used mostly in activity graphs. Provides communication capability between parallel processes. Put On Roof Build Frame Install Foundation Install Walls Inspect * * Install Electricity in Foundation Install Electricity In Frame Behavioral Modeling with UML Install Electricity Outside 136 Convenience Features (Synch State) ! ! Activity diagram notation Forks and joins do not require composite states. Synch states may be omitted for the common case (unlimited bound and one incoming and outgoing transition). Build Frame Put On Roof Install Walls Install Foundation Inspect Install Electricity in Foundation Install Electricity In Frame Behavioral Modeling with UML Install Electricity Outside 137 Convenience Features (Synch State) ! Object flow states can be synch states A11 A12 A13 Obj [S2] A21 A22 Behavioral Modeling with UML A23 138 Convenience Features ! Fork transitions can have guards. [ priority = 1] Evaluate Impact Revise Plan Register Bug Release Fix Fix Bug ! Test Fix Instead of doing this: [ priority = 1] Register Bug Evaluate Impact Revise Plan Release Fix [else] Fix Bug Test Fix Behavioral Modeling with UML 139 Convenience Features ! ! ! ! Partitions are a grouping mechanism. Swimlanes are the notation for partitions. They do not provide domain-specific semantics. Tools can generate swimlane presentation from domain-specific information without partitions. Management Evaluate Impact Revise Plan [ priority = 1] Support Register Bug Release Fix Engineering Fix Bug Test Fix Behavioral Modeling with UML 140 Convenience Features ! Signal send icon Wake Up Signal ! ! … translates to a transition with a send action. Signal receipt icon Turn on Coffee Pot Get Cups Coffee Pot Signal ! … translates to a wait state (a state with no action and a signal trigger event). Behavioral Modeling with UML Coffee Done Drink Coffee 141 partition Submission Team action state Task Force Revision Task Force initial state control flow Begin Adapted from Kobryn, “UML 2001” Communications of the ACM October 1999 Case Study fork of control Develop technology specification conditional fork Issue RFP RFP [issued] join of control Submit specification draft [optional] Collaborate with competitive submitters object flow Specification [initial proposal] input value Evaluate initial submissions Finalize specification Specification [final proposal] Behavioral Modeling with UML 142 Collaborate with competitive submitters Evaluate initial submissions Finalize specification Case Study Specification [final proposal] Evaluate final submissions Vote to recommend guard Specification [adopted] [YES] [NO] decision Revise specification Adapted from Kobryn, “UML 2001” Communications of the ACM October 1999 Implement specification Specification [revised] Enhance specification [else] Recommend revision [Enhanced] Behavioral Modeling with UML final state 143 When to Use Activity Diagrams ! Use activity diagrams when the behavior you are modeling ... ! ! ! ! does not depend much on external events. mostly has steps that run to completion, rather than being interrupted by events. requires object/data flow between steps. is being constructed at a stage when you are more concerned with which activities happen, rather than which objects are responsible for them (except partitions possibly). Behavioral Modeling with UML 144 Activity Diagram Modeling Tips ! ! ! Control flow and object flow are not separate. Both are modeled with state transitions. Dashed object flow lines are also control flow. You can mix state machine and control/object flow constructs on the same diagram (though you probably do not want to). Behavioral Modeling with UML 145 Activity Diagram Modeling Tips From UML User Guide: Customer Telesales Accounting Warehouse Request Return Get Return Number Ship Item Receive Item Item [returned] Restock Item Credit Account Behavioral Modeling with UML Item [available] 146 Customer Telesales Accounting Warehouse Request Return Get Return Number Activity Modeling Tips Ship Item Receive Item Item [returned] Restock Item Credit Account Behavioral Modeling with UML Item [available] 147 Activity Diagram Modeling Tips ! ! ! ! Activity diagrams inherit from state machines the requirement for well-structured nesting of composite states. This means you should either model as if composite states were there by matching all forks/decisions with a correspond join/merges … … or check that the diagram can be translated to one that is well-nested. This insures that diagram is executable under state machine semantics. Behavioral Modeling with UML 148 Activity Diagram Modeling Tips Well-nested: Behavioral Modeling with UML 149 Activity Diagram Modeling Tips Not well-nested: Apply structured coding principles. (Be careful with goto’s!) Behavioral Modeling with UML 150 Activity Diagram Modeling Tips Can be translated to well-nested diagram on earlier slide: Behavioral Modeling with UML 151 Wrap Up: Activity Diagrams ! ! ! ! ! Use Activity Diagrams for applications that are primarily control and data-driven, like business modeling … … rather than event-driven applications like embedded systems. Activity diagrams are a kind of state machine until UML 2.0 … … so control and object/data flow do not have separate semantics. UML 1.3 has new features for business modeling that increase power and convenience. Check it out and give feedback! Behavioral Modeling with UML 152 Preview - Next Tutorial ! Advanced Modeling with UML ! ! ! Model management Standard elements and profiles Object Constraint Language (OCL) Behavioral Modeling with UML 153 References ! ! [UML 1.3] OMG UML Specification v. 1.3, OMG doc# ad/06-08-99 [UML 1.4] OMG UML Specification v. 1.4, UML Revision Task Force recommended final draft, OMG doc# ad/01-02-13. Behavioral Modeling with UML 154 Further Info ! Web: ! ! ! ! ! UML 1.4 RTF: www.celigent.com/omg/umlrtf OMG UML Tutorials: www.celigent.com/omg/umlrtf/tutorials.htm UML 2.0 Working Group: www.celigent.com/omg/adptf/wgs/uml2wg.htm OMG UML Resources: www.omg.org/uml/ Email ! ! [email protected] Contributors: ! ! ! ! ! Gunnar Övergaard: [email protected] Bran Selic: [email protected] Conrad Bock: [email protected] Morgan Björkander: [email protected] Conferences & workshops ! ! ! UML World 2001, New York, June 11-14, 2001 UML 2001, Toronto, Canada, Oct. 1-5, 2001 OMG UML Workshop 2001, San Francisco, Dec. 3-6, 2001 Behavioral Modeling with UML 155
© Copyright 2025 Paperzz