当前位置:网站首页>UML series article (22) advanced behavior -- state machine

UML series article (22) advanced behavior -- state machine

2022-06-09 06:47:00 CoderIsArt

Content of this chapter :

  • state 、 Transfers and activities
  • Modeling the life cycle of an object
  • Create well structured algorithms

Use interaction , You can model the behavior of groups of objects working together . Use state machine , You can model the behavior of a single object . A state machine is a behavior , It describes the sequence of states an object experiences in its life cycle in response to events and its response to those events .

State machines are used to model the dynamic aspects of a system . in the majority of cases , This includes describing a class 、 The lifetime of a use case or an entire system instance . These instances may respond to signals such as 、 To manipulate or time such an event . When the event occurs , Some effects will occur depending on the current state of the object . effect (effect) Is a specification for the execution of actions in a state machine . Finally, the effect will be refined into the execution of some actions that cause the state of the object to change or the value to be returned . Object state (state) An object satisfies certain conditions , A period of time during which certain activities are performed or certain events are waited for .

There are two ways to visualize the state of execution : One is to emphasize the control flow from activity to activity ( Use activity diagrams ), The other is to emphasize the transfer between the potential states of the object ( Use statecharts ).

A well - structured state machine is like a well - structured algorithm : Simple 、 Efficient 、 Easy to adapt and understand .

1. introduction

stay UML in , Use elements such as class diagrams and object diagrams to model static aspects of the system . These diagrams allow you to view things in the system ( Including class 、 Interface 、 artifacts 、 node 、 Use cases and their examples ) And the relationship between them 、 detailed 、 Construct and document .

    stay UML in , Use the state machine to model the dynamic aspects of the system . Interaction is the object group modeling that completes certain actions together , The state machine models the life cycle of a single object , Whether it is a class 、 The use case is also an example of the whole system . In the life cycle of an object , Various events may occur , Like a signal 、 Call of operation 、 Object creation and revocation 、 The passage of time or the change of certain conditions . In response to these events , Objects through certain actions ( Some kind of calculation ) To respond , These actions cause the state of the object to change . therefore , The behavior of such an object is influenced by the past , At least when the past is reflected in the current state . An object can receive an event , And respond with an action , Then change its state . An object can also receive another event , Different responses are made according to the current state generated in response to the previous event .

    You can use a state machine to model any element ( It's usually a class 、 Usage 、 Or the whole system ) Behavior modeling . State machines can be visualized with state diagrams . You can focus on the behavior of objects triggered by events , This is very useful for reactive system modeling .

    UML Provides information about status 、 Transfer 、 Graphical representation of events and effects , Here's the picture ( State diagram of temperature control system ) Shown . This notation allows you to visualize the behavior of an object in a way that emphasizes important elements in its lifecycle .

2. Terms and concepts

    State machine (state Machine) It's an act , It describes the sequence of states an object experiences in its life cycle in response to events and their responses to those events . state (state) A condition or condition in the life cycle of an object , In the meantime, the object will satisfy certain conditions 、 Perform certain activities or wait for certain events . event (event) It is the stipulation of a meaningful occurrence that occupies a certain position in time and space . In the context of a state machine , An event is the occurrence of an incentive , It can trigger a state transition . A shift (transition) It's a relationship between two states , It indicates that the object performs certain actions in the first state , And enter the second state when a specific event occurs or a specific condition is met . Activities (activity) Is a non atomic execution in the state machine . action (action) Is an executable atomic computation , It causes the model state to change or the value to return . On the graph , The state is represented by a rounded rectangle , The transition is represented by a directed solid line from the original state to the new state .

2.1 context

    Each object has a lifetime . Creation time , An object is born ; When undone, an object terminates its existence . In between , One object can act on other objects ( Or by being the target of a message ) Affected . in many instances , These messages will be simple 、 Synchronous operation calls . for example , class Customer An instance of may be called in the class BankAccount Operations on an instance of getAccountBalance. Objects like this don't need a state machine to describe their behavior , Because their current behavior does not depend on their past .

    In other kinds of systems , You may encounter objects that must respond to signals , These signals are asynchronous messages that communicate between instances . for example , A mobile phone must respond to random calls ( From other phones )、 Key events ( From customers , Start a phone call ) And events from the Internet ( When the phone goes from one call to another ). Similarly , You will also encounter objects whose current behavior depends on past behavior . for example , The behavior of an air-to-air missile guidance system depends on its current state . Such as NotFlying( When the plane carrying the missile is still on the ground , Launching missiles is not a good idea ) or Searching( Before the target is determined , There is no need to equip with missiles ).

    State functions best illustrate that an object's behavior must respond to asynchronous messages , Or its current behavior depends on the past . This includes instances of classes that can receive signals , This includes many active objects . actually , An object received a signal , But there is no transfer for this signal in the current state , Without delaying the signal , Then it will simply ignore this signal . let me put it another way , Not transferring for a signal is not an error , It just means that you are not interested in the signal at that point . You can also use state machines to model the behavior of the entire system , Especially for reactive systems , Such systems must respond to signals from participants outside the system .

There are two points that need to be explained :

1) Most of the time , Interaction diagrams will be used to model the behavior of usage cases , But you can also use a state machine for the same purpose .

2) Similarly , State machines can be used to model the behavior of interfaces . Although the interface does not have any direct instances , But the class that implements this interface can have instances . Such a class must follow the behavior described by the state machine of the interface .

2.2 state

    A state is a condition or condition in the life of an object , In the meantime, the object will satisfy certain conditions 、 Perform certain activities or wait for certain events . The object stays in a state for a limited time . for example , Room heaters (Heater) May be in the following 4 Any of these states : Free (Idle)---- Wait for the command to start heating the room ; start-up (Activating)---- The hot air is turned on , But wait to reach a certain temperature ; Activities (Active)---- Both the hot gas and the blower are on ; close (ShuttingDown)---- Hot gas off , But the blower is on , Blow away the residual heat of the system .

    When the state machine of an object is in a given state , Say that this object is in this state . for example ,Heater An instance of might be in Idle, Or may be in ShuttingDown state .

    A state has the following parts :

1) name (name). A text string that distinguishes this state from other states ; States can be anonymous , That is, there is no name .

2) Get into 、 Exit effect (entry/exit effect). Actions performed when entering and exiting the state respectively .

3) Internal transfer (internal transition). A transition that does not result in a change of state .

4) Substate (substate). Nested structure of states , Include non orthogonal ( Sequential activities ) Or orthogonal ( Concurrent activities ) Substate .

5) Delay events (deferred event). It means that it will not be processed in this state , A list of events that will be deferred to another state of the object .

Use a rounded rectangle to represent a state .

Initial and final states

    As shown in the figure , There are two special states that may be defined in the state machine of an object . The first is the initial state , Indicates the default start position of the state machine or sub state . The initial state is represented by a solid circle . The second is the final state , Indicates that the execution of the state machine or peripheral state has been completed . The final state is represented by a circle with a solid circle inside ( Bovine eyes ).

2.3 Transfer

    Transition is a relationship between two states , Indicates that an object will perform certain actions in the first state when a specific event occurs and a specific condition is met , And enter the second state . When the state changes like this , Transfer is called activation . Before transfer activation , Say the object is in the source state ; After activation , The object is said to be in the target state . for example , When tooCold( With parameters desiredTemp) When such an event occurs ,Heater Probably from Idle The state shifts to Activating state . 

A transfer is made by 5 Part of it is made up of :

1) Source state (source state)

The source state is the state affected by the transition , If an object is in the source state , When the object receives the transferred event and the monitoring condition ( If there is ) When satisfied , A detached transfer will be activated .

2) Event trigger (event trigger) It's an event , The source state object recognizes this event , Then the transfer will be activated when the monitoring conditions are met .

3) Guardianship conditions (guard condition) It's a Boolean expression , When a transfer is triggered due to the receipt of an event trigger , Evaluate this Boolean expression : If the expression value is true, the transfer is activated ; If false, it will not activate , At this time, if no other amount transfer can be triggered by this event , The event is lost .

4) effect (effect) Is an executable behavior ( Like action ), It can act directly on objects that have state machines , And indirectly act on other objects that are visible to the object .

5) Target state (target state) That is, the activity status after the transfer is completed .

As shown in the figure below , A transition is represented by a directed solid line from the source state to the target state . Self transfer refers to the transfer with the same source state and target state .

annotation : A transition may have multiple sources ( under these circumstances , It represents a confluence from multiple concurrent states ), There may also be multiple goals ( In this case , It represents a bifurcation to multiple concurrent States ).

  • Event trigger

An event is a specification for a meaningful occurrence that occupies a certain position in time and space . In the context of a state machine , Events can trigger the occurrence of state transition incentives . As shown in the figure , Events can include signals 、 call 、 A change in time or state . A signal or call can take parameters , Parameter value pair transfer ( Including the expression of monitoring conditions and actions ) Is visible .

    It may also be possible to complete the transfer , It is represented by a transition without an event trigger . Completion transition completes its behavior in the source state ( If there is ) Is implicitly triggered .

annotation :

Event triggers can be polymorphic . for example , If a signal family is defined , So a trigger event is S The transfer of can be S Trigger , Can also be S Any subclass triggers .

  • Guardianship conditions    

The monitoring condition is represented by a Boolean expression enclosed in square brackets , After the trigger event . The monitoring condition is calculated only after the trigger event that caused the transfer . As long as the monitoring conditions do not overlap , There may be from the same source state 、 Multiple transitions with the same event trigger .

    For each transfer , A monitoring condition is calculated only once when an event occurs , But if the transfer is triggered again , The monitoring conditions will be recalculated . Boolean expressions can contain conditions about the state of an object ( for example , Expression is aHeater in Idle, If the object Heater The current in the Idle state , Then its value is true ). If the conditions do not hold when calculating , Then the event will not happen when the conditions are established . Model this behavior with change events .

  • effect

    The effect is the behavior performed when the transfer is activated . Effects include online calculations 、 Operation call ( Call the object that owns the state machine or other visible objects )、 The creation or revocation of another object , Or send a signal to an object . To indicate that a signal is sent , You can add a keyword before the signal name send As a visual cue .

    The transition only occurs when the state machine is stationary , That is, when it no longer performs the effect from the previous transfer . The effects of a transfer and any associated entry and exit effects must be performed , To allow another event to trigger a new transfer . by comparison ,do Activities can be interrupted by events .

2.4 Advanced states and transitions

    stay UML in , Only the basic characteristics of States and transitions can be used to deal with a wide range of 、 Modeling various behaviors . Use these features , Eventually, a simple state machine can be generated , It means that there are no arcs in the behavior model ( Transfer ) And vertex ( state ) It doesn't include anything else .

    However ,UML The state machine has many advanced features that can help manage complex behavior models . These features can often reduce the number of States and transitions required , And bring together many common and somewhat complex idioms encountered when using simple state machines . These advanced features include the entry effect 、 Exit effect 、 Internal transfer 、do Activity and delay events . These features are displayed as a text string in the text column of the status symbol , Here's the picture

1) Entry effect and exit effect

    In many modeling cases , Whenever you enter a state , Whatever moves you into , They all want to perform a certain setting action ; Again , When leaving a state , Whatever moves you away , They all want to perform a certain cleanup action .

for example , In a guidance system , May want to : Whenever it enters Tracking In the state of , Declare explicitly that the system is onTrack Of ; Whenever it leaves this state , Declare that the system is offTrack Of . Use a simple state machine , This effect can be achieved by placing those actions on each corresponding entry and exit transfer . However , There is a danger of mistakes , You have to remember to add these actions every time you add a new transition . and , Modifying this action means having to touch each adjacent transition .

    UML Provides a concise representation of this idiom . Include an entry effect in the status symbol ( keyword entry Mark ) And an exit effect ( keyword exit Mark ), Each with an appropriate action . Whenever you enter this state , Just execute its entry action ; Whenever you leave this state , Just execute its exit action .

    Entry effect and exit effect cannot have parameters or monitoring conditions . However , The entry effect of the top layer in the state of a class can have parameters , Used to represent the parameters received by the state machine when the object is created .

2) Internal transfer

    Once in a state , You will encounter events that you want to handle without leaving the State , This is called internal transfer , It is slightly different from self transfer . In self transfer , As shown above , After the event triggers the transfer , Left this state , An action ( If there is ) Be performed , And then re-enter the same state . Because this transition exits first and then enters this state , therefore , The self transfer executes the exit action of the state first , Then perform the self transfer action , Finally, execute the entry action of this state .

      Suppose you want to handle this event , But I don't want to perform the entry and exit actions of this state ,UML Internal transfer provides a convenient way for this usage . Internal transfer (internal transition) It is such a transfer : It responds to events by executing an effect , But do not change the state . In the diagram above , event NewTarget Identifies an internal transfer : If the object is in Tracking This event occurs when the status is , Then perform the action Tracker.acquire, But the status remains unchanged , And no entry or exit actions are performed . Internal transfers are not indicated by transfer arrows , Instead, it is represented as a transition string inside the status symbol ( Include the event name , Optional monitoring conditions and effects ). It should be noted that , keyword entry、exit、 and Do It's all reserved words , Cannot be used as the name of an event . If the object is in a certain state , And an internal transition event of the state occurs , Then execute the corresponding effect , Without leaving and entering the state again . therefore , Such events are handled without invoking state exit and entry actions .

annotation : Internal transfer can have events with parameters and monitoring conditions .

3)do Activities

    When an object is in a state , It is usually idle , Waiting for an event to happen . But sometimes , You may want to model an ongoing activity . While in a state , Objects do some work , And continue until interrupted by an event . for example , If an object is in Tracking state , As long as it is in this state , It will carry out followTarget. stay UML Use special do Transition to describe the work done within a state after the entry action is performed . It can also explain a behavior , Such as action sequence -----do/op1(a); op2(b); op3(c);. If the occurrence of an event results in a transition from the current state , So the current state is any ongoing do The activity will stop immediately .

4) Delay events

    In various modeling situations , You may want to identify some events , And ignore other events . Identify events that act as triggers for the events of the transition , Ignore events that are thrown away directly . However, in some modeling cases , You may want to receive some events , But delay responding to it later . for example , When in Tracking In the state of , You may want to delay the response selfTest Such a signal , They may be sent by some maintenance agent in the system .

    stay UML in , Delay events can be used to describe this behavior . A delay event is an event whose processing is delayed in this state , Do not process another state until it is activated . If this event is not delayed in that state , Then the event will be handled as if it had just happened and may trigger a transfer . If the state machine passes a series of delays to the state of the event , Then the event will remain until a state occurs that will not delay the event .

annotation : The implementation of deferred events requires an internal event queue . If an event happens , And is listed as a delay event , Then enter the queue . Once the object enters a state that does not delay these events , These events are removed from the queue .

5) Sub state machine

You can reference another state machine in one state machine . The referenced state machine is called a sub state machine (substatemachine)

This is useful in building large structured state models .

2.5 Substate

    These advanced features of state and transition solve many common state machine modeling problems . However ,UML The state machine has another feature , I.e. sub state , It can help simplify the modeling of complex behaviors . A child state is a state nested in another state . for example , A heater Heater May be under heating Heating state , And in Heating There is also a nested state in the state Activating. under these circumstances , It should be said that this object is both in Heating state , Again in Activating state .

      A simple state is a state without substructures . A containing a substate ( That is, nested state ) The state of is called a composite state . Composite states include concurrency ( Orthogonal ) Substate or sequence ( Not orthogonal ) Substate . stay UML in , Representing a composite state is like representing a simple state , But also use an optional graphical column to display a nested state machine . Child states can be nested at any level .

1) Non orthogonal substate

 

2) The state of history

 

3) Orthogonality state

 

4) Bifurcation and confluence

 

5) Active object

    Another way to model concurrency is to use active objects . therefore , Instead of dividing the state machine of an object into two or more concurrent regions , Instead, define two active objects , Each is responsible for the behavior of a concurrent region . If one of these concurrent control flows is affected by the state of other control flows , Let's use orthogonal regions to model . If the behavior of one of these concurrent flows is affected by messages with other control flows , Will be active object modeling . If there is little or no communication between concurrent streams , Usually active object modeling makes design decisions more obvious .

3. Common modeling techniques

The general purpose of using state machines is to model the life cycle of objects . Interaction models the group behavior of objects working together , The state machine models the behavior of a single object throughout its lifetime . Mainly describe the following three things : Events that the object can respond to 、 The response to these events and the impact of the past on current behavior .

When modeling the life cycle of an object , Follow these strategies :

  • Set the context of the state machine
  • Establish the initial and final states of the object .
  • Determine the event that may respond .
  • From the initial state to the final state , List the top-level states that this object may be in .
  • Identify any entry and exit actions .
  • if necessary , These states are augmented by sub states .
  • By tracking the state machine , Check against the expected sequence of events and their responses . Try to find the unreachable state and the state that causes the machine to stop .

The following figure shows the state machine of the safety system controller

    In the lifetime of this controller class, there are 4 There are four main states :“”“ initialization ”Initializing( The controller starts running )、“ Free ”Idle( The controller is ready , And wait for an alarm or a command from the user ) 、“ command ”Command( The controller is processing commands from the user ) and “ Activities ”Active( The controller is processing an alarm condition ).

    When this controller object is first created , First of all to enter Initializing state , Then enter unconditionally Idle state . The details of these two states are not displayed , But to show Idle Self transfer with time events in the state . This kind of time event is common in embedded systems , It often has a heartbeat timer , Check the health of the system every once in a while .

    When an alarm is received alarm When an event is , Control from Idle The state shifts to Active state .

Get into Active In the state of ,setAlarm Execute as an entry action , Control is first transmitted to Checking state ( Verify this alert ), And then transmit to Calling state ( Call the alarm company to register this alarm ), Finally, it is transmitted to Waiting state . Only when the “ eliminate ”clearing Alarm time , Or the user sends a message to the controller “ Be careful ”attention Signals to inform that a command may be issued are , To exit the status Active and Waiting.

    Notice that there is no end state . It is also common in embedded systems , The system is expected to run indefinitely .

4. Tips and techniques

A well structured state machine , The following requirements shall be met :

  • Simple
  • Clear context
  • It works
  • Understandable
  • Don't nest too deeply
  • Use the orthogonal substate sparingly ( Active classes are often a better choice )

draw UML State machine , Follow these strategies :

  • Avoid crossing transfer lines
  • Only when it is necessary to understand the graph can the composite state be extended .
原网站

版权声明
本文为[CoderIsArt]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090625345486.html