Vous êtes sur la page 1sur 18

Unit 3

OOMD

Advanced state modeling


Nested state diagrams 1) Problems with flat state diagrams State diagrams have been criticized because they are impractical for large problems. This problem is true for flat, unstructured Diagram. Consider an object with n independent Boolean attributes that affect control. Representing such an object with a single flat state diagram would require 2 n states. By partitioning the state into n independent state diagrams only 2n states are required. Consider the state diagram in this figure

Figure: combinatorial explosion of transitions in flat state diagrams. This figure requires n2 transitions needed to connect every state to every other state. If this model is reformulated by using structure, the number of transitions will be reduced to n. 2) Expanding states One way to organize a model is by having a high level diagram with subdiagrams expanding certain states

VendingMachine coins in(amount) / set balance Idle cancel / refund coins Collecting money coins in(amount) / add to balance select(item) [change<0]

[item empty]

do / test item and compute change [change=0] dispense: DispenseItem [change>0] do / make change

Figure: Vending machine state diagram. Initially, the vending machine is idle. When a Person inserts coins, the machine adds amount to the cumulative balance. After adding some coins, a person can select an item. If the item is empty or the balance is

insufficient, the machine waits for another selection. Otherwise, the machine dispenses the item and returns the appropriate change. Figure elaborates the dispense state with a lower-level state diagram called a submachine. A submachine is a state diagram that may be invoked as part of another state diagram. The UML notation for invoking a submachine is to list a local state name followed by a colon and the submachine name. This is submachine of previous state diagram UML notation of invoking submachine is local state name followed colon and submachine name.
DispenseItem do / move arm to correct row pushed arm ready do / move arm to correct column

arm ready do / push item off shelf

Figure: Dispense item submachine of vending machine. Nested States States can be structured either by submachine or alternatively by nesting. A composite state name labels the outer contour that entirely encloses the nested states. Active is composite state and dial tone timeout and dialing are nested state.
PhoneLine onHook / disconnectLine Idle offHook Active DialTone do / soundDialTone digit(n) digit(n) Dialing BusyTone do / slowBusyTone numberBusy timeout timeout invalidNumber Recorded Message do / playMessage Timeout do / soundLoudBeep

Warning do / play message

validNumber

Connecting do / findConnection FastBusyTone do / fastBusyTone trunkBusy routed Ringing do / ringBell calledPhoneAnswers Connected calledPhoneHangsUp / disconnectLine Disconnected / connectLine messageDone

Figure: Nested states for a phone line We can nest states to an arbitrary depth.

CarTransmission Neutral push N Forward stop First upshift Second downshift

push R Reverse push N push F upshift Third downshift

Signal Generalization We can organize signals into generalization hierarchy with inheritance of signal attributes. Figure shows part of the tree of input signals for a workstation. A signal hierarchy permits different levels of abstraction to be used in a model. signal UserInput

device

signal MouseButton location

signal KeyboardCharacter character

signal MouseButtonDown

signal MouseButtonUp

signal Control

signal Graphic

signal Space

signal Alphanumeric

signal Punctuation

Figure: partial hierarchy for keyboard signals. Concurrency The state model implicitly supports concurrency among objects. Objects are autonomous entities that can act and change independent of one another. 1) Aggregation concurrency 2) concurrency within an object 3) Synchronization of concurrent activities. Aggregation concurrency A state diagram for an assembly is a collection of state diagrams, one for each part. The aggregate state corresponds to the combined states of all the parts. Aggregation is the and-relationship. The aggregate state is the one state from the first diagram, and from the second diagram, and a state from each other diagram.

Car
1 1 1 1 1

Ignition Ignition Off

Transmission

Accelerator

Brake

turn key to start [Transmission in Neutral] Starting turn key off

release key On

Transmission Neutral

push R Reverse push N push N push F

Forward stop First downshift upshift Second downshift upshift Third

Accelerator depress accelerator Off release accelerator On

Brake depress brake Off release brake On

Figure: An aggregation and its concurrent state diagrams Concurrency within an object We can partition some objects into subsets of attributes or links, each of which has its own sub diagram. The state of the object comprises one state from each sub diagram. The sub diagrams need not to be independent; the same event can cause transitions in more than one sub diagram. The UML shows concurrency within an object by partitioning the composite state into the regions with dotted lines. We should place the name of the composite state in a separate tab so that it does not become confused with the concurrent regions.

Figure: Bridge game with concurrent states. Synchronization of concurrent activities

Sometimes one object must perform two (or more) activities concurrently. The object does not synchronize the internal steps of the activities but must complete both the activities before it can progress to its next state. Splitting control in to concurrent activity and later on merging control. U notation a small heavy bar with one input arrow and two or more output arrows for fork. Event/guard condition can label arrow o/p arrow have no label For merge/join same. Two concurrent sub states

Figure: Synchronization of control. A completion transition from outer composite state to another state indicates implicit merging of concurrent control. A completion transition is fired when activity in source state is complete. A composite concurrent state is complete when each of its concurrent sub state is complete when each of them has reached its final state. A sample state model for programmable thermostat. Figure: state model for programmabl e thermostat

Figure: Sub diagram for thermostat user interface.

Figure: Sub diagram for thermostat user interface setup. Interaction modeling It is third leg of modeling tripod. It Describes interaction within a system Class model: describes object within a system State model: describes life cycle of objects Interaction model: describes how objects interact to produce useful results State model Vs Interaction model Both are needed to describe behaviors fully They complement each other Use Case Models o Used at high level o Describes how a system interacts with out side actors o Helpful to capture informal requirements Sequence Diagrams models o Provide more detail and show the messages exchanged among a set of objects over a period of time o Messages can be asynchronous signals or procedure calls Activity Diagram models o Can show data flow as well as control flow

Use case Models 1. Actors


An actor is a direct external user of a system that communicates directly with the system but that is not part of the system. Each actor represents those objects that behave in a particular way toward the system. For example: customer and repair technician are different actors of a vending machine.

An object can be bound to multiple actors if it has different facests to its behavior. An actor has a single well defined purpose. Each actor represents a coherent set of capabilities for its objects. 2. Use cases The various interactions of actors with a system are quantized into use cases .A use case is a coherent piece of functionality that a system can provide interacting with the actors. Each use case involves one or more actors as well as the system itself. A Use case involves a sequence of messages among the system and its actors. Error conditions are also the part of a use case.

Buy a beverage . The vending machine delivers a beverage after a customer se lects and pays for it. Perform scheduled maintenance . A repair technician performs the periodic service on the vending machine necessary to keep it in good working condition. Make repairs. A repair technician performs the unexpected service on the vend ing machine necessary to repair a problem in its operation. Load items . A stock clerk adds items into the vending machine to replenish its stock of beverages.

Figure: Use case summaries for a vending machine.

Use case description

Use Case: Buy a beverage Summary: The vending machine delivers a beverage after a customer selects and pays for it. Actors: Customer Preconditions: The machine is waiting for money to be inserted. Description: The machine starts in the waiting state in which it displays the message Enter coins. A customer inserts coins into the machine. The machine displays the total value of money entered and lights up the buttons for the items that can be pur chased for the money inserted. The customer pushes a button. The machine dispenses the corresponding item and makes change, if the cost of the item is less than the mon ey inserted. Exceptions: Canceled: If the customer presses the cancel button before an item has been selected, the customers money is returned and the machine resets to the waiting state. Out of stock: If the customer presses a button for an out-of-stock item, the message That item is out of stock is displayed. The machine continues to accept coins or a selection. Insufficient money: If the customer presses a button for an item that costs more than the money inserted, the message You must insert $ nn.nn more for that item is dis played, where nn.nn is the amount of additional money needed. The machine contin ues to accept coins or a selection. No change: If the customer has inserted enough money to buy the item but the ma chine cannot make the correct change, the message Cannot make correct change is displayed and the machine continues to accept coins or a selection. Postconditions: The machine is waiting for money to be inserted.

Figure: Use Case description

4. Use case Diagrams


A system involves a set of use cases and a set of actors. Each use case represents a slice of the functionality the system provides. The set of use cases shows the complete functionality of the system at some level of detail. Similarly each actor represents one kind of object for which the system can perform behavior. The set of actors represent the complete set of objects that the system can serve. The UML has a graphical notation for summarizing use cases and shows an example.
Vending Machine buy beverage Customer perform scheduled maintenance Repair technician

make repairs

load items Stock clerk

Figure: Use case diagram for a vending machine. 5. Guidelines for Use Case Models First determine the system boundary Ensure that actors are focused Each Use case must provide value to users Relate use cases and actors Remember that use cases are informal Use cases can be structured.

Sequence models
Sequence of events that occurs during one particular execution of a system. It can be in various forms. It may include all events in a system. It may include only those events generated by certain objects. It can be historical record Thought experiment normally shown as list of text statements. There are two kinds of sequence models. scenario and A more structured format called sequence diagrams Scenario can be displayed as a list of text statements.

John Doe logs in. System establishes secure communications. System displays portfolio information. John Doe enters a buy order for 100 shares of GE at the market price. System verifies sufficient funds for purchase. System displays confirmation screen with estimated cost. John Doe confirms purchase. System places order on securities exchange. System displays transaction tracking number. John Doe logs out. System establishes insecure communication. System displays good-bye screen. Securities exchange reports results of trade.
Figure: Scenario for a session with an online stock broker. A Scenario contains messages between objects as well as activities performed by objects. Each message transmits information from one object to another. Sequence diagrams Scenario is a convenient for writing but it does not convey complete information. If there are more than two objects it does not clearly show sender and receiver of each message. Sequence diagram shows the participants in an interaction and the sequence of messages among them. Sequence diagram shows the interaction between actors in a system to perform all or part of a use case Figure shows the sequence diagram corresponding to the previous stock broker scenario. Each actor as well as the system is represented by a vertical line called as a lifeline and each message by a horizontal arrow from the sender to the receiver. Time proceeds from top to bottom, but spacing is irrelevant. The diagram shows only the sequence of messages, not their exact timing.

:Customer log in

:StockBrokerSystem

:SecuritiesExchange

secure communication display portfolio enter purchase data request confirmation confirm purchase display order number logout insecure communication display good bye

{verify customer}

{verify funds}

place order

{execute order}

report results of trade

Figure: Sequence diagram for a session with an online stock broker. Different sequence diagrams can be done between the same actors but with different independent tasks. Sequence diagram for stock purchase.
:Customer :StockBrokerSystem :SecuritiesExchange

enter purchase data request confirmation confirm purchase display order number place order report results of trade {execute order} {verify funds}

Figure: Sequence diagram for stock purchase.

:Customer

:StockBrokerSystem

:SecuritiesExchange

enter stock symbol request stock data report stock data display quote

Figure: Sequence diagram for a stock quote When to draw sequence diagrams To show different activities between actors For clear depiction of scenarios For more clarity on use cases In case of unlimited number of scenarios effort should be done to provide sequence diagram covering maximum use cases Exception handling sequence diagrams must be done separately Avoid redundancy and repetition of information amongst sequence diagrams Guideline for sequence models Prepare at least one scenario per use case Abstract scenarios into sequence diagrams Divide complex interactions Prepare sequence diagrams for each error condition Activity models An activity diagram shows the sequence of steps that make up a complex process, such as an algorithm or workflow. An activity diagram shows flow of control, similar to a sequence diagram, but focuses on operations rather than on objects. Activity diagram are most useful during the early stages of designing algorithms and workflows. Activity diagram for stock trade processing. It is like traditional flowchart but unlike flowchart it can also show concurrent flow of control.

Figure: Activity diagram for stock trade processing 1. Activities Steps of activity diagram are operations. Mostly activities are from state model. Some activities run for ever, but most activities eventually complete their work and terminate Activity diagram for execute order. An activity can be decomposed to finer activities
[market order] [timeout] [selling] [buying] [limit order] [order still active] [price not available] find buyer at market price find seller at market price [selling] [price available] [buying]

find buyer at limit price or better

find seller at limit price or better

Figure: Activity diagram for execute order. 2. Branches If there is more than one successor to an activity then each arrow must be labeled with a condition in square brackets. Eg [failure].One of the condition must be satisfied to perform one of the successor activities. If none of the condition satisfies then system hangs and its bad design. To avoid this else condition can be used i.e. the default activity if none of the condition is satisfies. If more than one branch satisfies condition then there is no surety of which activity will be performed this type of overlapping conditional branches must be avoided by designer. UML notation uses diamond as branch symbol. 3. Initiation and termination A solid circle with an outgoing arrow shows starting point. A bulls eye shows the termination point. 4. Concurrent activities Fork and merge shown by heavy bars 5. Executable activity diagrams

Activity token can be placed on an activity symbol to denote that it is executing. Guidelines for activity model Dont misuse activity model : Only meant to elaborate use case and sequence model must not be used to develop s/w via flowcharts Level diagram properly Be careful with branches and conditions Consider executable activity diagrams Advanced Interaction Modeling The interaction model has several advanced features that can be helpful. 1. Use case Relationships Include relationship The include relationship incorporates one use case within the behavior sequence of another use case. An included use case is like a subroutine-it represents behavior that would otherwise have to be described repeatedly. The UML notation is dashed arrow from source use case to target use case. Keyword <<include>> annotates the arrow Include lets a base use case incorporate behaviors from inclusion use case
secure session include validate password make trade include

Figure: Use case inclusion Extend Relationship Extend relationship adds incremental behavior to a use case. It is like an include relationship looked at from the opposite direction, in which extension adds itself to the base rather than the base explicitly incorporating the extension. It represents the frequent situation in which some initial capability is defined, and later features are added modularly to the Include Relationship and extend Relationship. It connects an extension use case to a base use case.

trade stocks extend extend margin trading short sale


Figure: Use case Extension

trade options extend extend limit order

Generalization Generalization can show specific variations on a general use case, analogous to generalization among classes. A parent use case represents a general behavior sequence. Child use cases specialize the parent by inserting additional steps or by refining steps. The UML indicates Generalization by an arrow with its tail on the child use case and a triangular arrowhead on the parent use case, the same notation that is used for classes. For example, an online stock brokerage system.

make trade

trade bonds

trade stocks

trade options

Figure: Use case generalization Combinations of use case relationships


Customer Securities exchange

Stock Brokerage System secure session

include

include

include

manage account

make trade

include validate password

extend

limit order

trade bonds extend extend

trade stocks extend short sale

trade options

margin trading

Guidelines for Use case relationships Use case generalization Use case inclusion Use case Extension Include relationship vs. extend relationship 2. Procedural sequence Models Most implementations are procedural and limit the number of objects that can execute at a time. The UML has elaborations for sequence diagrams to show procedure calls. Sequence Diagrams with Passive objects With procedural code all objects are not constantly active. Most objects are passive and do not have their own threads of control. A passive object is not activated until it has been called. Once the execution of an operation completes and control returns to the caller, the Passive object becomes inactive.

:Transaction compute commission ( )

:CustomerTable

:RateTable

service level (customer) level calculate commission (level, transaction) commission commission

Figure: sequence diagrams with passive objects. The UML shows the period of time for an objects execution as a thin rectangle. This is called the activation or focus of control. Sequence diagram with transient objects
objectA operationE (c, d) createC (arg) objectB

objectC

operationE (m, n) {execute order}

resultT

resultV

Guidelines for procedural sequence model Active Vs. Passive objects : Most objects are passive and lack their own thread of control Advanced features Special constructs for activity model Sending and receiving signals Swimlanes Object flows 1. Sending and receiving signals Activity diagram can show fine control via sending and receiving events Signal: When an activity sends or receives a message then that activity is called as signal. Signal is of two types namely: The UML notation for an input and output signal are given by: Input Signal: Message receiving activity shown by a concave polygon Output Signal: Message sending activity shown by a convex polygon

Figure: Sending and receiving signals

2. Swimlanes Activity diagrams provide another ability to clarify which actor performs which activity. We can show such a partitioning with an activity diagram by dividing it into column and lines. Each column is called a swimlane analogy to a swimming pool

Flight attendant

Ground crew

Catering

clean trash

add fuel

load food and drinks

Figure: Swimlane 3. Object flows The relationship between an operation and the objects that are its argument values or results. The activity diagram can show objects that are input to or output from the activities.

:Airplane [at gate]

leave gate

:Airplane [taxiing]

take off

:Airplane [in flight]

:Airplane [at gate]


Figure: Object flow

park at gate

:Airplane [taxiing]

landing

Vous aimerez peut-être aussi