Vous êtes sur la page 1sur 290

Prsentation UML

Unified Modeling Language Pascal Molli Universit Nancy1,Loria molli@loria.fr, www.loria.fr/~molli

Bibliographie
s s s s s s s s

UML Distilled Fowler&Scott UML Toolkit Eriksson&Penker Applyling UML and Patterns Larman Design pattern GOF System of patterns Buschman&al Penser objet avec UML&Java Lai Object oriented Analysis Spadounakis UML Specification www.rational.com
Pascal Molli, molli@loria.fr 2

Introduction et vue densemble


Analyse des besoins (Requirements Analysis) Analyse (analysis) Conception (design) Codage (Programming) Test
s

s s s s s

UML:Produire des documents Pertinent Consistent Comprhensible Facile changer Pour tout le cycle de vie

Pascal Molli, molli@loria.fr

Pourquoi UML ?
s

s s

crire des documents pour communiquer, travailler plusieurs Comprendre la big picture Continuer son apprentissage OO.

Pascal Molli, molli@loria.fr

La guerre des Mthodes


s

Booch, OMT, Coad/Yourdon, Fusion,SADT, OOSE, Schlaer/Mellor, HOOD UML: un mta-langage de modlisation pour unifier les modles utiliss dans les mthodes Grady Booch, Ivar Jacobson, James Rumbaugh. Standardisation OMG

Pascal Molli, molli@loria.fr

Analyse des besoins


s s

Capturer les besoins des utilisateurs diagramme Use-Case en UML


Student Select Courses to Teach Professor Register for Courses

Billing System

Pascal Molli, molli@loria.fr

Analyse
s s

Indpendant de limplmentation ! Identification des classes et des relations Description des collaborations entre les objets des diffrentes classes Diagramme de classes, de collaboration, d activits, d tat.
Pascal Molli, molli@loria.fr 7

Conception (design)
s

Prise en compte de larchitecture informatique Classes techniques pour grer l interface graphique, la distribution, la persistence, la concurrence Diagramme de classes, de squences, de composant, de dploiement, d tats
Pascal Molli, molli@loria.fr 8

Programmation
s

Conversion des classes de conception vers les langages cibles: java, sql, c++, IDL Conversion des classes persistentes vers les modles de persistences (SGBD, BDOO, Langages persistents) etc ...
Pascal Molli, molli@loria.fr 9

Test
s s

Tests unitaires: diagrammes de classes Tests d intgration: diagrammes de composants, de collaboration Test du systme: use-case diagram

Pascal Molli, molli@loria.fr

10

Un premier exemple
s s s

Un jeu de ds Le joueur lance 10x 2 ds Si le total fait 7, il marque 10 points son score En fin de partie, son score est inscrit dans le tableau des scores.

Pascal Molli, molli@loria.fr

11

Analyse des besoins


s s s

Un premier Use-case Identifier les acteurs? Identifiers les cas dutilisations possibles du systme Ses fonctionnalits externes !

Pascal Molli, molli@loria.fr

12

Premier Use Case


s
P la y P la ye r

Play:
Acteur: Player Descr: Le joueur prend 10x les ds, chaque fois que le total fait 7, +10pts

V ie w Hig h S co re

View High Score


Acteur: Player Descr: Le joueur consulte en read only les high score

Pascal Molli, molli@loria.fr

13

Use Case
s s s

s s

Diagramme extrmement important ! IMHO, Il doit figurer dans un cahier des charges Il doit figurer dans toute prsentation d une application ! IL DOIT TRE COMMENTE de manire rigoureuse ! Sert de rfrence pour toute la suite des oprations

Pascal Molli, molli@loria.fr

14

Diagramme d activit
s

Ressemble furieusement aux vieux organigramme identifier les activits (en s appuyant sur use case) identifier les transitions entre activits

Pascal Molli, molli@loria.fr

15

Diagramme d activit
m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] 16

[highscore] view Highscor e

[exit]

Update highscore Pascal Molli, molli@loria.fr

Diagramme d activit
[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [exit]

Play Player

View High Score

[true]

Tu rn <1 0 [false] Update highscore

Pascal Molli, molli@loria.fr

17

Diagramme d activit
m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] Update highscore Pascal Molli, molli@loria.fr

[highscore] view Highscor e

[exit]

18

Diagramme dactivit
s

s s

Phase analyse des besoins ou analyse? Plus business process que orient objet Ordonnance et dtaille les Usecase Trs utile pour les tests...

Pascal Molli, molli@loria.fr

19

Analyse
s s s

Modliser le monde rl Indpendant de l implantation Dterminer les classes d objets du monde rl : premier diagramme de classe Modliser la dynamique du systme: diagramme de collaboration.
Pascal Molli, molli@loria.fr 20

Diagramme de collaboration
s s

Identifier les OBJETS les relations entre OBJETS (graphe d objets) les message et l ordre d appel des messages entre les objets

Pascal Molli, molli@loria.fr

21

Diagramme de collaboration
d1 : D ie 2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer

s s

Visualise les objets Visualise les relations entre objets Visualise l ordonnancement des appels de messages sur les objets
22

Pascal Molli, molli@loria.fr

Digramme de collaboration
[highscore] view Highscor e m e n u [start] Start turn=0
d1 : D ie

[exit]

Roll Dice turn++ [true] Tu rn <1 0 [false]

2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer

Update highscore Pascal Molli, molli@loria.fr

23

Diagramme de classes
s s

s s s

Identifier les classes Identifier les relations statiques et dynamiques entre les classes Dterminer les cardinalits des relations Dterminer les attributs des classes Dterminer les mthodes et leurs paramtres
Pascal Molli, molli@loria.fr 24

Diagramme de classes
Player
(from Use Case View)

Rolls 1 2

name : String score : int = 0; play() 1 Plays 1

Die faceValue : int = 1 roll() 1

Includes DiceGame 1 1

Scoring 1 HighScore

Pascal Molli, molli@loria.fr

25

Diagramme de classes
P layer
d1 : D ie 2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer
(from Us e Cas e V iew)

R olls 2

name : S tring score : int = 0; 1 play() 1 P lays 1 D iceGame 1 1

D ie faceV alue : int = 1 roll() 1

Includes

S coring 1 HighS core

Pascal Molli, molli@loria.fr

26

Diagramme de squences
s

Modlise la dynamique (~comme collaboration) Focalise sur lenchanement des messages Identifier les objets, les messages et leur ordonnancement.

Pascal Molli, molli@loria.fr

27

Diagramme de squences
: DiceGame : Player d1 : Die d2 : Die

1: play( )

2: roll( ) 3: roll( )

Dure d activation !
Pascal Molli, molli@loria.fr 28

Diagramme de squences
d1 : D ie 2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer
: DiceGame : Player d1 : Die d2 : Die

1: play( )

2: roll( ) 3: roll( )

Rfrence!
Pascal Molli, molli@loria.fr 29

Diagramme de squences
: RealPlayer : DiceGame d1 : Die d2 : Die : Player 1: DiceGame( ) 2: Die( )

3: Die( )

4: start( ) 5: Player(String)

Le joueur n est cr quau dmarrage de la partie !


Pascal Molli, molli@loria.fr 30

Diagramme d tats
s s

Identifier les tats d un objet Identifier les transitions entre les tats

Pascal Molli, molli@loria.fr

31

Diagramme dtat dun objet partie


cancel / Start game Ready to play start

Player ready entry: get player name

Quit play roll dices[ turn<10 ]

Cancel

[ turn>=10 ]

In progress entry: turn++

Pascal Molli, molli@loria.fr

32

Diagramme dtat
[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] Update highscore

Cancel ?
ca ncel / S tart game Ready to play start

[exit]

Player ready e ntry: ge t player name

Quit play roll dices[ turn<1 0 ]

Cancel

[ turn>=10 ]

In progress entry: turn++

Cancel ?
Pascal Molli, molli@loria.fr 33

Modifier les schmas...


m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] 34

[highscore] view Highscor e

[exit]

cancel cancel

Update highscore Pascal Molli, molli@loria.fr

Modifier les schmas ?


m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] Update highscore Pascal Molli, molli@loria.fr

[highscore] view Highscor e

[exit]

35

Analyse termine ?
s

s s

Vrifier la couverture des diagrammes use-case et d activits Use case view highscores ? Use case play partiellement trait.

Pascal Molli, molli@loria.fr

36

Couverture des diagrammes


[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [exit]

Play Player

View High Score

[true]

Partiellement trait
Pascal Molli, Pas trait molli@loria.fr

Tu rn <1 0 [false] Update highscore 37

Diagramme de squences
: RealPlayer : DiceGame 2: Die( ) d1 : Die d2 : Die : HighScore 1: DiceGame( )

3: Die( ) 4: Highscore( )

Pascal Molli, molli@loria.fr

38

Diagramme de squence
: DiceGame : Player d1 : Die d2 : Die new : Entry : HighScore 1: Player(String)

2: play( ) 3: roll( ) 4: roll( ) 5: Entry(name:String,score:int)

6: add(Entry)

Pascal Molli, molli@loria.fr

39

Diagramme de classes
<<Actor>> Player name : String score : int = 0; play() Player() Rolls 1 1 Plays 2 Die faceValue : int = 1 roll() Die() 1 1 DiceGame DiceGame() 1 start() 1 Scoring 1 HighScore Highscore() 1 add() 0..* Includes

Entry name:String : type = initval score:int : type = initval Entry(name:String,score:int)()

Pascal Molli, molli@loria.fr

40

Fin de lanalyse ?
s s s

Couverture un peu prs bonne Cohrence entre les schmas correcte 14/20
La dynamique manque de dtail (dynamique du cancel ?) Les schmas sont trop peu expliqus Les diagrammes de squence du jeu ne sont pas assez dtaills : manque quelques mthodes...

Pascal Molli, molli@loria.fr

41

Conception
s

Prendre en compte l implmentation


Grer la partie interface graphique Grer la persistance des highscores

s s s

Dfinir une architecture logique Dfinir une architecture physique Rajouter les classes techniques permettant d implanter cette architecture !
Pascal Molli, molli@loria.fr 42

Conception de larchitecture
Prsentation

Applicatif
Play

View High Score

Persistance

Fichier ou BDD
Pascal Molli, molli@loria.fr 43

Architecture en couche...
s

Une architecture possible, d autres existent (voir A system of patterns Bushcmann ) Les couches doivent tre le plus indpendante possible Dcoupler les couches en s appuyant sur interfaces + classes abstraites (design patterns)
Pascal Molli, molli@loria.fr 44

Dcoupage en package logique


<<layer>> UI

<<layer>> Core

<<subsystem>> Util

Mapper l architecture sur des packages layer Exprimer les dpendances

<<layer>> Persist

Pascal Molli, molli@loria.fr

45

Layer core
s

Les classes reprsentant la logique de notre application. En fait, les classes d analyses revisites en vue de la ralisation

Pascal Molli, molli@loria.fr

46

Core Layer :1er diagramme


Design
HighScore $ hs : HighScore = null Highscore() add() load() save() 1 0..* Entry name:String : type = initval score:int : type = initval Entry(name:String,score:int)()

Analyse
<<Actor>> Player name : String 1 score : int = 0; play() Player() Plays1 Rolls 2 Die faceValue : int = 1 roll() Die() 1

DiceGame $ dg = null DiceGame() getInstance() start() 2 -dies Die faceValue : int = 1 roll() Die() display()

Singleton...

1 DiceGame DiceGame() 1 start() 1 Scoring

Includes

-player 1 Player name : String score : int = 0; Player() display()

1 HighScore Highscore() 1 add() 0..*

Entry name:String : type = initval score:int : type = initval Entry(name:String,score:int)()

Pascal Molli, molli@loria.fr

47

Dcouplage interface graphique:MVC


Observable
(from util)

changed : boolean = false Observable() addObserver() deleteObserver() notifyObservers() notifyObservers() deleteObservers() setChanged() clearChanged() hasChanged() countObservers() <<Interface>> Observer
(from util)

0..*

update(o : Observable, arg : Object) : void

Die
(from Core)

faceValue : int = 1 Player


(from Core)

DieView DieView(die : Die) update(o : Observable, arg : Object) : void

roll() Die() display() PlayerView PlayerView(player : Player) update(o : Observable, arg : Object) : void

name : String score : int = 0; Player() display()

Pascal Molli, molli@loria.fr

48

Vues ?
(from util)

<<Interface>> Observer

update(o : Observable, arg : Object) : void

DieView DieView(die : Die) update(o : Observable, arg : Object) : void

PlayerView PlayerView(player : Player) update(o : Observable, arg : Object) : void

Pascal Molli, molli@loria.fr

49

Attention...
Observable
(from util)

changed : boolean = false Observable() addObserver() deleteObserver() notifyObservers() notifyObservers() deleteObservers() setChanged() clearChanged() hasChanged() countObservers() <<Interface>> Observer
(from util)

0..*

update(o : Observable, arg : Object) : void

Panel
(from awt)

Panel() Panel() constructComponentName() addNotify() Die


(from Core)

faceValue : int = 1 roll() Die() display() setValue() PlayerView PlayerView(player : Player) update(o : Observable, arg : Object) : void

DieView DieView(die : Die) update(o : Observable, arg : Object) : void

Player
(from Core)

name : String score : int = 0; Player() display()

Pascal Molli, molli@loria.fr

50

MVC en action:1 mise en place


: RollForm 1: display( ) : Playe : PlayerV iew : Die : DieView 2 : PlayerVie w(Player)

3: addObserver(Observer) 4: return component 5: display()

6: DieView(Die) 7: addObserver(Observer)

8: return component

Pascal Molli, molli@loria.fr

51

MVC en action:2 changement d tat


: Die : Randomizer 1: getValue( ) 2: setValue(int) 3: notifyObservers( ) : DieView

4: update(Observable, Object)

Pascal Molli, molli@loria.fr

52

MVC
s

AWT Java: Modle par dlgation


Propagation des vnements de l IHM vers les classes applicatives (core ici)

MVC:
Propagation des changements d tats vers les objets graphiques

Pascal Molli, molli@loria.fr

53

Mettre les vues dans des forms


s

Raliser des crans graphiques contenant des vues si il y a lieu Le layer UI...

Pascal Molli, molli@loria.fr

54

UI Layer

Frame
(from awt)

PlayerForm ok_action() cancel_action() PlayerForm() 0..1 MainForm HighScoreForm ok_action() quit_action() start_action() high_action() MainForm() 1 PlayerView HighScoreView update() <<Interface>> Observer
(from util)

RollForm roll_action() 0..1 cancel_action() RollForm()

DieView DieView() update()

PlayerView() update()

update() Molli, molli@loria.fr Pascal

55

Mapping classe UI, UI


PlayerForm ok_action() cancel_action() PlayerForm()

MainForm quit_action() start_action() high_action() MainForm() 1 PlayerView PlayerView() update() 2 DieView DieView() update() RollForm roll_action() 0..1 cancel_action() RollForm()

Pascal Molli, molli@loria.fr

56

Diagramme d objets:rollform
d1 : Die View : Roll Form theDieView theDieView d2 : Die View : Label : Label

momo : thePlayerView PlayerView

: Label

: Label : Panel roll : Button cancel : Button

Pascal Molli, molli@loria.fr

57

: RealPlayer

: DiceGame

: MainForm

: PlayerForm

: Playe

: RollForm

1: getInstance( )

2: MainForm( )

3: start_action( ) 4: PlayerForm( )

5: ok_action( ) 6: start( String playerName) 7: Player(String) 8: RollForm( )

Pascal Molli, molli@loria.fr

58

: RollF orm 1: display( )

: P laye

: P layerV iew

: D ie

: D ieV iew

2 : PlayerVie w(Player)

3: addObserver(Observer) 4: return com ponent 5: display()

6: D ieV iew(D ie) 7: addObserver(Observer)

8: return com ponent

Pascal Molli, molli@loria.fr

59

Dcouplage UI/Core...
HighScore $ hs : HighScore = null Highscore() add() load() save() 1 0..* Entry name:String : type = initval score:int : type = initval Entry(name:String,score:int)()

<<Interface>> Displayable display()

DiceGame $ dg = null DiceGame() getInstance() start() 2 -dies Die faceValue : int = 1 roll() Die() display() setValue()

Singleton...

-player 1 Player name : String score : int = 0; Player() display()

Pascal Molli, molli@loria.fr

60

Architecture en couche...
RollForm

Classes techniques UI
DieView 2

(from UI)

roll_action() cancel_action() RollForm()

+thePlayerView PlayerView
(from UI)

UI

(from UI)

+theDieView

1 PlayerView() update()

DieView() update()

Interface et classes abstraite de dcouplage

<<Interface>> Displayable

Observable
(from util)

<<Interface>> Observer 0..*


(from util)

Core
Classes d analyses

Die faceValue : int = 1 roll() Die() display() setValue()

Player name : String score : int = 0; Player() display()

Pascal Molli, molli@loria.fr

61

Util subsystem
s s

Besoin de nombres alatoires Utiliser fonctionnalit random de java.util Le gnrateur de nombre alatoire est partag par tous les ds Encore un singleton...

Pascal Molli, molli@loria.fr

62

Subsystem util
Random
(from util)

Singleton

$ serialVersionUID : long = 3905348978240129619L seed : long $ multiplier : long = 0x5DEECE66DL $ addend : long = 0xBL $ mask : long = (1L << 48) - 1 $ BITS_PER_BYTE : int = 8 $ BYTES_PER_INT : int = 4 nextNextGaussian : double haveNextNextGaussian : boolean = false Randomizer getInstance() getValue() 1 Random() Random() setSeed() next() nextBytes() nextInt() nextInt() nextLong() nextBoolean() nextFloat() nextDouble() nextGaussian()

Pascal Molli, molli@loria.fr

63

Dynamique de Util
: Player : Die : Randomizer : Random 1: roll( ) 2: getInstance( ) 3: Randomizer( )

4: Random( )

Singleton ! 5: getValue( )

6: nextInt(int)

Pascal Molli, molli@loria.fr

64

Layer Persist
s s

Classes techniques de persistances Assurer l indpendance Core/Persist


pouvoir changer de persistent engine

Par exemple:
Persistance par Serialisation Persistance via une base de donnes relationnelle (JDBC).
Pascal Molli, molli@loria.fr 65

Dcouplage : Pattern Fabrication


HighScore
(from Core)

Produit abstrait

$ hs : HighScore = null Highscore() add() load() save()

Produit concret

HighS coreJDB C Highscore() load() save()

HighScoreSr $ filename : String = "/tmp/high.score" Highscore() load() save()

Fabrique concrte

JdbcKit makeKit()

SrKit makeKit()

Fabrique abstraite

PersistKit

Pascal Molli, molli@loria.fr

makeKit()

66

Dynamique de Persist
: RealPlayer : DiceGame : SrKit : HighScoreSr 1: SrKit( ) Attention! DiceGame voit SrKit comme un PersistKit et HighScoreSr comme un HighScore

2: getInstance( ) 3: DiceGame( )

4: makeKit( )

5: HighScoreSr( ) 6: load( )

Seul le Realplayer sait qu'il utilise un SrKit ! DiceGame non !

7: quit( )

8: getInstance( ) 9: save( )

Pascal Molli, molli@loria.fr

67

Utiliser la sralisation
s

Propagation de persistance...
e1 : Entry

: High Score

e2 : Entry

e3 : Entry

e4 : Entry

Pascal Molli, molli@loria.fr

68

Un peu de codethats all folks


class HighScoreSr extends HighScore implements Serializable { ... public void save() throws Exception { FileOutputStream ostream = new FileOutputStream(filename); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(this); // Write the tree to the stream. p.flush(); ostream.close(); // close the file. } public void load() throws Exception { FileInputStream istream = new FileInputStream(filename); ObjectInputStream q = new ObjectInputStream(istream); HighScoreSr hsr = (HighScoreSr)q.readObject(); } }
Pascal Molli, molli@loria.fr 69

Dynamiqe de JdbPersist...
s s

Une table doit tre cre dans un SGBD relationnel la cration de HighScoreJDBC: Connection au SGBD via JDBC save:
faire des inserts pour chaque entry

load:
Select * from ..., parcours du rsultat, cration des objets entry

Pascal Molli, molli@loria.fr

70

Un peu de code...
public class HighScoreJDBC extends HighScore { public static final String url="jdbc:odbc:dice"; Connection con=null; public HighScoreJDBC() { try { //loads the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection(url, "molli",""); } catch (Exception e) { e.printStackTrace(); new Error("Cannot access Database at"+url); } hs=this; // register unique instance ! this.load(); }
Pascal Molli, molli@loria.fr 71

Jdbc Load
public void load() { try { Statement select=con.createStatement(); ResultSet result=select.executeQuery ("SELECT Name,Score FROM HighScore"); while (result.next()) { this.add(new Entry(result.getString(1), result.getInt(2))); } } catch (Exception e) { e.printStackTrace(); } }

Pascal Molli, molli@loria.fr

72

Jdbc Save
public void save() { try { for (Enumeration e = this.elements() ; e.hasMoreElements() ;) { Entry entry=(Entry)e.nextElement(); Statement s=con.createStatement(); s.executeUpdate( "INSERT INTO HighScore (Name,Score)"+ "VALUES('"+entry.getName()+"',"+ entry.getScore()+")"); } } catch (Exception e) { e.printStackTrace(); } }
Pascal Molli, molli@loria.fr 73

Component diagram...
s

a component is a non-trivial, nearly independent, and replaceable part of a system that fulfills a clear function in the context of a well-defined architecture. A component conforms to and provides the physical realization of a set of interfaces.
Pascal Molli, molli@loria.fr 74

Component diagram
s

s s

Realize : implmenter des interfaces Depend : Utiliser les intefaces Les interfaces dcouplent les composants

Pascal Molli, molli@loria.fr

75

Component diagram...
DicePersist HighScore Observable PersistKit Observer DiceSystem Displayable Dice Vizua lizatio n

Rand om izer

Random system

Pascal Molli, molli@loria.fr

76

Diagrammes de dploiement
s s

Visualiser l architecture physique Associer les units d excution aux traitements Identifier les connexions entre les units d excution

Pascal Molli, molli@loria.fr

77

Diagramme de dploiement
JBDC Connection Save/load the highscore

Game Computer SGBD computer

Play the game

File System

Maybe a Remote a file system

Pascal Molli, molli@loria.fr

78

Design termin ?
s

Couverture des fonctionnalits : comparer Use-case et activity diagram Cohrence entre les diagrammes ??
Quelques incohrences UI vs Core Indpendance Core/Persist partiellement atteinte...
Pascal Molli, molli@loria.fr 79

Gnrer le code : code mapping


s s

s s

Mapper vers n importe quel langage ! Les langages objets : java, C++, smalltalk Mais aussi les autres: VB, C, Fortran Voir aussi: SQL, Cobol...

Pascal Molli, molli@loria.fr

80

package Core;

Mapping java...
<<Interface>> Displayable display() Observable
(from util)

import import import import

Util.Randomizer; UI.DieView; java.util.*; java.awt.Component;

public class Die extends Observable implements Displayable { private int faceValue = 1; public int roll() { setValue(Randomizer.getInstance(). getValue()); return getValue(); } public java.awt.Component display() { Component c=new DieView(this);

Die faceValue : int = 1 roll() : int Die() display() : java.awt.Component setValue(value : int) : void getValue() : int

this.addObserver((Observer)c); return c; } public void setValue(int value) { faceValue=value; this.setChanged(); this.notifyObservers(); } public int getValue() { return faceValue;} Pascal Molli, molli@loria.fr 81 }

Relations

HighScore
(from Core)

$ hs : HighScore = null Highscore() add() load() save() getInstance() 1

Entry +schedule name:String : type = initval score:int : type = initval 0..* Entry(name:String,score:int)()
(from Core)

package Core; import java.util.*; import java.awt.Component; import UI.HighScoreView; public abstract class HighScore extends Observable implements java.io.Serializable, Displayable { protected static HighScore hs = null; public Vector entries=new Vector(); public void add(Entry entry) { entries.addElement(entry); this.setChanged(); this.notifyObservers(); }

public Enumeration elements() { return entries.elements(); } public abstract void load(); public abstract void save(); public Component display() { Component c=new HighScoreView(this); this.addObserver((java.util.Observer)c); return c; } public static HighScore getInstance() { if (hs==null) { new Error("No Persist Kit declared"); } return hs;} Pascal Molli, molli@loria.fr 82

Codage...
s

s s

Utiliser les fonctionnalits de forward engineering des outils Puis de reverse engineering Pour faire en fait du round trip engineering ;-D Assurer la cohrence Code/Design/analyse...
Pascal Molli, molli@loria.fr 83

Forward engineering
Die Player
(from Core) (from Core)

faceValue : int = 1 roll() Die() display() setValue() -dies 2

name : String score : int = 0 Player() display() -thePlayer

+theDiceGame DiceGame
(from Core)

$ dg = null DiceGame() getInstance() start() quit()

// Source file: c:/prout/Core/DiceGame.java package Core; public class DiceGame { private static int dg = null; private Die dies[]; private Player thePlayer; DiceGame() { } /** @roseuid 37F877B3027B */ private DiceGame() { } /** @roseuid 3802F61403A0 */ public void getInstance() { } /** @roseuid 37F8781A014D */ public void start() { } /** @roseuid 38074E7F0158 */ public void quit() { } }

Pascal Molli, molli@loria.fr

84

Forward Engineering
: RealPlayer : DiceGame : SrKit 1: SrKit( )

package Core; import UI.MainForm; import Persist.*; import java.awt.*; class Main { public static void main(String args[]) { // SrKit srk=new SrKit(); JdbcKit srk=new JdbcKit(); DiceGame dg=DiceGame.getInstance(); Frame f=MainForm.getInstance(); f.setSize(300,300); f.show(); } }

2: getInstance( ) 3: DiceGame( )

4: makeKit( )

Pascal Molli, molli@loria.fr

85

Reverse Engineering...
Observable
(from util)

Vector
(from util)

Die faceValue : int = 1 roll() Die() display() setValue() getValue() -dies[]

+entries

Player score : int = 0 turn : int = 0 WIN_NUMBER : int = 7 WIN_SCORE : int = 10

Entry score : int Entry() getName() getScore() toString()

HighScore HighScore() add() elements() load() save() display() getInstance()

Player() die1() DiceGame die2() -thePlayer play() display() DiceGame() getName() getInstance() getScore() start() getTurn() getDie() setTurn() getPlayer() -$dg setScore()

#$hs

-name -name String


(from lang)

Pascal Molli, molli@loria.fr

86

Reverse engineering
s s

Rien sur la dynamique ! Gre les aspects forward+modification+reverse Pas miraculeux !

Pascal Molli, molli@loria.fr

87

Comparaison Design/Ralisation
Observable
(fro u m til)

Vector
(from util)

String
(from lang)

CORE
Die faceValue : int = 1 roll() Die() display() setValue() getValue() -dies[] HighScore HighScore() add() elements() load() save() display() getInstance()

+entries

-name -name

#$hs

Player score : int = 0 turn : int = 0 WI N_NU MBER: int = 7 WI N_SCO E : int = 10 R Play er() die1() die2() play () display() getName() getScore() getTurn() setT urn() setScore()

Entry score : int Entry() getName() getScore() toString()

-thePlayer

DiceGame DiceGame() getInstance() start() getDie() getPlayer() -$dg <<Interface> > Displayable display()

Pascal Molli, molli@loria.fr

88

UI(1)
HighScoreForm

ActionListener
(from event)

Frame
(from awt)

actionPerformed() HighScoreForm() -hf closeAction() -mf MainForm

TextField
(from awt)

RollForm actionPerformed() rollAction() cancelAction() RollForm()

-rf

actionPerformed() quitAction() +m_MainForm startAction() highAction() +m_MainForm MainForm() getInstance() -$mf

-tf

-pf

PlayerForm actionPerformed() okAction() cancelAction() PlayerForm()

-close -start -quit +ok -high -ok +cancel -cancel Button


(from awt)

Pascal Molli, molli@loria.fr

89

UI(2)
HighScoreForm actionPerformed() HighScoreForm() closeAction() +m_HighScoreForm +cancel +ok -close Button
(from awt)

RollForm actionPerformed() rollAction() cancelAction() RollForm() -m_RollForm +m_RollForm

+theDieView[] -hv HighScoreView HighScoreView() update() DieView() update() -l DieView +thePlayerView PlayerView -scoreLabel -nameLabel -turnLabel Label
(from awt)

PlayerView() update()

-l List
(from awt)

Observer
(from util)

Pascal Molli, molli@loria.fr

90

Util
Randomizer -$r getInstance() getValue() Randomizer() Random -random util) (from

Pascal Molli, molli@loria.fr

91

Persist
S erializable
(from io)

D iceGame
(from Core)

E ntry H ighS core


(from Core) (from Core)

P ersistK it #$pk P ersistK it() getInstance() m akeK it()

-$dg D iceGam e() getInstance() start() getD ie() getP layer()

score : int E ntry() getNam e() getS core() toS tring()

V ector + entries (from util) HighS core()#$hs add() elem ents() load() save() display() getInstance()

HighS coreJD B C HighS coreJD B C () load() save() JdbcK it JdbcK it() m akeK it() S rK it m akeK it() S rK it() loa d() sa ve () H ighS coreS r()

HighS coreS r

Pascal Molli, molli@loria.fr

92

Problmes rencontrs
s

Dynamique de la gestion des tours mal conue ! Qui vritablement fait le test de fin de jeu ? Faiblesse dans le design !

Pascal Molli, molli@loria.fr

93

Ici ! Diagramme d analyse !!


: DiceGame : Player d1 : Die d2 : Die new : Entry : HighScore 1: Player(String)

2: play( ) 3: roll( ) 4: roll( ) 5: Entry(name:String,score:int)

6: add(Entry)

Pascal Molli, molli@loria.fr

94

Problme !
s s

Pas assez rigoureux ! Ce diagramme d analyse n a pas t revu au design !!! (-4)

Pascal Molli, molli@loria.fr

95

Refaire !
: RollForm : Player : Die : Die 1: actionPerformed(ActionEvent) 2: rollAction( )

3: getTurn( )

4: [turn<10]play( )

5: setValue(int) 6: setValue(int)

7: setTurn(int)

Pascal Molli, molli@loria.fr

96

Finalement !

Pascal Molli, molli@loria.fr

97

Est ce que a marche ? Tester


s

Tests unitaires : tester classe par classe, mthode par mthode


Diagramme de classes

Tests d intgration :
diagramme de composants

Tests du systme :
Diagramme Use Case + Activits
Pascal Molli, molli@loria.fr 98

Test du systme
s
P la y P la ye r

s
V ie w Hig h S co re

Ok, les fonctionnalits sont l ... et sont conformes au descriptif associ au use case ! >8->

Pascal Molli, molli@loria.fr

99

Je l ai oubli

Test du systme
[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false] Update highscore Pascal Molli, molli@loria.fr [exit]

celui l !

100

Test du systme
[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [true] Tu rn <1 0 [false]

s
[exit]

Tester tous les chemins possibles ! Ex:


1/Start 2/ roll 3/ cancel 4/ highscore 5/ exit
101

Update highscore Pascal Molli, molli@loria.fr

Problme rencontr
s

Scnario 1 :
start, roll*, highscore, quit : OK

Scnario 2:
highscore, : ko ! Bug Pb design :
DiceGame cre Highscore (start) Si Highscore avant start : bug

Pascal Molli, molli@loria.fr

102

Solution
package Core; import UI.MainForm; import Persist.*; import java.awt.*; class Main { public static void main(String args[]) { // SrKit srk=new SrKit(); JdbcKit srk=new JdbcKit();

DiceGame dg=DiceGame.getInstance();
Frame f=MainForm.getInstance(); f.setSize(300,300); f.show(); } }
Pascal Molli, molli@loria.fr 103

Test d intgration
DicePersist HighScore Observable PersistKit Observer DiceSystem Displayable Dice Vizua lizatio n

Rand om izer

Random system

Test MVC

Pascal Molli, molli@loria.fr

104

Scnario de test
s s

s s

Highscore, start, roll* Si le MVC fonctionne, l entre d un nouveau highscore entrane le raffichage de la liste qui est dj ouverte !! Ok, a marche C est bien de bien designer ...
Pascal Molli, molli@loria.fr 105

Debriefing de cette application


s

Analyse des besoins


Use-case + description diagramme d activits Prototypage UI

Analyse
Dynamique : Collaboration, Sequence, state Statique : Class Diagram
Pascal Molli, molli@loria.fr 106

Design
s

Architecture design (layer)


Package diagram, component diagram, deployement diagram

Classes techniques pour assurer le dcoupage :


Pattern MVC, Pattern Fabrication

Classes Techniques UI et persistance


*Forms, Highscore*

Pascal Molli, molli@loria.fr

107

Codage
s s

Simple conversion du design vers Java Possibilit de construire pour chaque reprsentation UML, une traduction vers n importe quel langage cible. Utilisation des outils pour round-trip engineering PB au codage : Bien remettre jour les document analyse/design !!!
Pascal Molli, molli@loria.fr 108

Remonter les PB vus au codage !


: RollForm : Player : Die : Die 1: actionPerformed(ActionEvent)

2: rollAction( )

3: getTurn( )

s
5: setValue(int) 6: setValue(int) 7: setTurn(int)

4: [turn<10]play( )

s s

Faire son auto-critique, retrouver la cause de ce pb.. Amliorer son process pour la prochaine fois ! Ici : les diag d analyse n ont pas t refait ! Software process, procdure qualit !

Pascal Molli, molli@loria.fr

109

Tests
s s

contrle des fonctionnalits :Use-case Contrle de la conformit: Diagramme d activit Tests d intgration : Diagramme de composant Tests unitaires : pas fait.

Pascal Molli, molli@loria.fr

110

Tests attention !
s s

Vision un peu simpliste des choses ! Intgration dans un process qualit (change management) Tests de rgression, automatisation des tests (banque de tests, gnration de test, outils!!)

Pascal Molli, molli@loria.fr

111

Conclusion sur cette application


s

Dcoupage en phase:
Analyse des besoins, analyse, conception, ralisation, test.

Dans chaque phase:


Prise de points de vue sur le mme problme Vue statique, dynamique, fonctionnelle, architecturale

Pascal Molli, molli@loria.fr

112

Vue Fonctionnelle
DicePersist

Vue architecturale
Dice Vizua lizatio n

DiceSystem HighScore

Displayable

P la y P la ye r

Observable P ersistKit Observer

V ie w H ig h S co re

F in d B e ve ra g e [ fo u n d c o ffe e ]

[ n o c o ffe e ]

[ n o c o la ]

[ fo u n d c o l a ]

P u t C o ffee in F il terA d d W a t e r t o R e s e rvo irG e t C u p s

G e t C an of C o la

Vue Statique
( fr o m U s e C a s e V R w )l l s ie o

P ut F ilt e r i n M a c h in e

Cohrence !! Couverture !!
1 : p la y ( ) g a m e : D ic e G am e

Vue Comportementale
d 1 : D ie 2 : r1 = ro ll( )

Rand omizer

Random system

JBDC Connection

Save/load the highscore

P la y e r

Game Computer SGBD computer

T u rn o n M a c h i n e

^c o ffe e P ot . T urn O n B re w C o ffe e

n a m e : S trin g s c o r e : in t 1 0 ; = p la y ( ) 1 P la ys 1
P ou r C o ffe e D rin k B e ve ra g e

D ie fa c e V a lu e : i n t = 1 2 r o ll( ) 1

3 : r2 = ro ll( ) d 2 : D ie

l ig h t g o e s o u t

In c lu d e s D ic e G a m e 1 1 S c o ri n g 1 H ig h S c o re
/ Start game Ready to play cancel

M o m o : P la y e r

Play the game

File S ystem

Maybe a Remote a file system

: DiceGame

: P laye r

d1 : Die

d2 : Die

1: play( )
start Player ready entry: get player name

2: roll( ) 3: roll( )

Quit play roll dices[ turn<10 ]

Cancel

[ turn>=10 ]

In progress entry: turn++

Pascal Molli, molli@loria.fr

113

Cohrence/couverture
s

Diagramme Use-cases/Activity
Une activit doit toujours tre assignable un use-case Tous les use-case doivent tre raliss dans les diagrammes d activits

Pascal Molli, molli@loria.fr

114

Use-case/Activity
[highscore] view Highscor e m e n u [start] Start turn=0 Roll Dice turn++ [exit]

Play Player

View High Score

[true]

OK !
Pascal Molli, molli@loria.fr

Tu rn <1 0 [false] Update highscore 115

Activits/Collaboration
s

s s

Tous les chemins possibles dans les diagrammes d activits sont sujet tre reprsents par des diagrammes de collaboration! Attention la sur-analyse ! Ne reprsenter que les scnarios les plus pertinents !
Pascal Molli, molli@loria.fr 116

Activit/collaboration
[highscore] view Highscor e m e n u [start] Start turn=0
d1 : D ie

1 collaboration diagram traitant partiellement Roll !!


[exit]

Roll Dice turn++ [true] Tu rn <1 0 [false]

2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer

Update highscore Pascal Molli, molli@loria.fr

117

Collaboration/Class diagram
s

Tous les objets d un diagramme de collaboration ont un type : Classe du diagramme de classe Les relations d un diagramme de collab doivent exister ou pouvoir tre drives du diagramme de classe ! Les messages changs sont des mthodes du diagrammes de classes !
Pascal Molli, molli@loria.fr 118

Collab class/Diagram
P layer
d1 : D ie 2: r1=roll( ) gam e : Dice Gam e 1: play( ) 3: r2=roll( ) d2 : D ie M om o : P layer
(from Us e Cas e V iew)

R olls 2

name : S tring score : int = 0; 1 play() 1 P lays 1 D iceGame 1 1

D ie faceV alue : int = 1 roll() 1

Includes

S coring

OK!
Pascal Molli, molli@loria.fr

1 HighS core

119

Class diagram /collab / squence


s

Toute la dynamique des relations doit apparatre dans au moins 1 diagramme de squence ou d activits Tout changement d attributs doit tre reprsents dans au moins 1 diag d activits ou de squence Toute cration ou destruction d objet doit apparatre dans au moins 1 diag dynamique!
Pascal Molli, molli@loria.fr 120

Class/Seqence
P la ye r
(from U s e C a s e V ie w )

KO!
: R e a lP la y e r : D ic e G a m e d 1 : D ie d 2 : D ie : P la y e r

R o lls 2

na m e : S tring s c o re : int = 01 ; p la y() 1 P la y s 1 D ic e G a m e 1 1

D ie fa c e V a lue : int = 1 ro ll() 1

1 : D ic e G a m e ( )

2 : D ie ( )

Changement d tat ?
In c lu d e s
4 : s ta r t( )

3 : D ie ( )

5 : P la y e r (S tri n g )

S c o rin g 1 H ig hS c o re

Cration ?
Pascal Molli, molli@loria.fr 121

Class/Squence
s

Une bonne solution:


Se laisser guider par l activity diagram pour gnrer les scnarios Bien faire les chemins possible dans l activity diagram Si le diagram de classes n est pas couvert:
Pas assez fine-grained (notre cas ici) Class diagram sur spcifi
Pascal Molli, molli@loria.fr 122

Class/State diagram...
s

s s

Pour chaque classe se demander si son statut volue au cours du temps ? Si oui, faire un diagramme d tat Attention chaque transition du diagramme d tat doit tre vrifie !

Pascal Molli, molli@loria.fr

123

Class/State diagram !
P la ye r
(from U s e C a s e V ie w )

Ou sont ces mthodes ? ?


c a nc e l s ta rt

R o lls 2

na m e : S tring s c o re : int = 01 ; p la y() 1 P la y s 1 D ic e G a m e 1 1

D ie fa c e V a lue : int = 1 ro ll() 1


/ S tart g a m e R e a d y to p la y

P la ye r re a d y e ntry : ge t play er nam e

In c lu d e s

Q uit p la y ro ll d ic e s [ tur n<1 0 ]

C a nc el

S c o rin g 1 H ig hS c o re

1 Objet DiceGame !

[ tur n>= 10 ]

In p ro g re s s e ntry: turn+ +

Ou est cet attribut ??


Pascal Molli, molli@loria.fr 124

Class/Package/Component diagram (Design)


s

Chaque classe doit tre affect un package, package lui-mme partie intgrante de l architecture Toute classe doit faire aussi partie d un composant assurant un ensemble de fonctionnalit dans cette architecture !! Sinon la classe ne fait pas partie de l architecture !
Pascal Molli, molli@loria.fr 125

Class/Package
awt (from java) MVC: Observer/Observable

Singleton

Random
(from util)
<<layer>> UI util (from java)

<<Interface>> Randomizer getInstance() getValue() Randomizer()

Random() Random() setSeed() next() nextBytes() nextInt() 1 nextInt() nextLong() nextBoolean() nextFloat() nextDouble() nextGaussian()

<<layer>> Core

<<subsystem>> Util

for random !

Random FUNCTION !

<<layer>> P ersist

Pascal Molli, molli@loria.fr

126

Class/Composant
DicePersist HighScore Observable PersistKit Observer D iceSystem Displayable Dice Vizua lizatio n

Singleton

Random
(from util)
Rand om izer

<<Interface>> Randomizer getInstance() getValue() Randomizer()

Random() Random() setSeed() next() nextBytes() nextInt() 1 nextInt() nextLong() nextBoolean() nextFloat() nextDouble() nextGaussian()

Random system

Pascal Molli, molli@loria.fr

127

Component/Deployement
s

Chaque composant doit tre affect une unit d excution sur le diagramme de dploiement ! A Priori, un composant ne peut pas tre cheval sur deux unit d excution Toute unit d excution doit avoir au moins 1 composant...
Pascal Molli, molli@loria.fr 128

Composant dploiement !
DicePersist HighScore Observable PersistKit Observer DiceSystem Displayable Dice Vizua lizatio n

OOOPPPPSS !
Save/load the highscore

JBDC Connection

Rand om izer

Random system

Game Computer SGBD computer

Play the game

File System

Maybe a Remote a file system

Pascal Molli, molli@loria.fr

129

Conclusion gnrale sur Dice


s

Diffrence avec une application juste code ??

Pascal Molli, molli@loria.fr

130

Analyser et concevoir ?
s

Dice est document : les dcisions autant l analyse quau design sont visibles et justifies (ici l oral, l crit dans vos rapport)!
Dice peut tre repris par quelqu un d autre ! Le cout de maintenance baisse! Dice est maintenable ! Dice peut tre control (intgr dans un software process) tout au long du processus analyse des besoins/tests...

Pascal Molli, molli@loria.fr

131

Analyser et concevoir
s

Dice est conforme : J ai dis ce que j allais faire (avant de le faire) et j ai fait ce j ai dit !
J aurai pu mme donner des dlais et des couts...

Pascal Molli, molli@loria.fr

132

Analyser et concevoir
s

Dice est volutif


On peut changer l IHM On peut rajouter un support de persistence (Mapping O2, Sauvegarde sur serveur WEB) Et je peux donner une procdure pour faire cette volution !

Pascal Molli, molli@loria.fr

133

Analyser et Concevoir
s

Dice est robuste:


Campagne de tests Apport naturel du MVC

Dice est portable:


Java + JDBC (mais non test !)

Pascal Molli, molli@loria.fr

134

Analyser et concevoir
s s

Dice est donc maintenable, conforme, robuste, portable Le cot de Dice est donc moins lev qu un Dice dvelopp Quick and Dirty .
Le cot de maintenance est bien plus lev que le cot de dveloppement (50% de l effort total de programmation d une grosse socit)

Pascal Molli, molli@loria.fr

135

Analyser et concevoir
s

Rpartition du cot de dveloppement d un systme: Phase Costs (%) Testing System type Requirements/ Coding
Command control Spaceborn Scientific Business OS Design 46 34 44 44 33 20 20 26 28 17 34 46 30 28 50

Pascal Molli, molli@loria.fr

136

Travailler avec des outils...


s

Dessin des diagrammes: En respectant la smantique des diagrammes Sert de rfrentiel: Tous les lments crs dans diffrents diagrammes sont stocks dans 1BD Navigation: browser travers les documents UML
Pascal Molli, molli@loria.fr 137

Travailler avec des outils...


s

Support multi-utilisateurs: Plusieurs utilisateurs doivent pouvoir travailler en parallle sur le mme modle (Gestion de configuration) Gnration de code: Gnration de squelettes dans diffrents langages cibles
Pascal Molli, molli@loria.fr 138

Travailler avec des outils


s

Reverse enginnering: lire le code existant et gnrer ou mettre jour les diagrammes existant Intgration avec les autres outils: Editeur, compilateur, debugger, gestionnaire de configuration

Pascal Molli, molli@loria.fr

139

Travailler avec des outils...


s

Couvrir le modle tous les niveaux d abstraction: des packages jusquau code Import/export: L outil doit permettre d importer/exporter des design de ou vers d autres outils de conception

Pascal Molli, molli@loria.fr

140

Un outil...

Pascal Molli, molli@loria.fr

141

Travailler avec des outils


s

Un rfrentiel pour:
Controler l incohrence Critiquer (mtriques) Reporting

En fait des scripts sur une base de donnes...

Pascal Molli, molli@loria.fr

142

Scripts...

Pascal Molli, molli@loria.fr

143

Intgration...
Project Management Tool Requirements and Specification tools Profiler and metrics Compilateu r/ Debugger Configuration Management

Documentatio n Tool

Modelling tool

Gui Builde r

Process Support

Testin g tools

Test Administration Tool

Pascal Molli, molli@loria.fr

144

De nouveau les diagrammes...


s

Reprenons les notations (Use-case, activity, class, sequence, collab, component, etc et voyons un peu les notations un peu plus exotiques

Pascal Molli, molli@loria.fr

145

Use Cases: Scenario based requirements modeling


s

Recommended: UML distilled...

Frank Maurer, University of Calgary

146

Use Cases
Use case s specifies the behavior of a system s sequence of actions to yield an observable result of value to an actor s Capture the intended behavior (the what) of the system omitting the implementation of the behavior (the how)
s

customer requirements/ early analysis


Frank Maurer, University of Calgary 147

What is a use case?


s s s

Description of a sequence of actions, including variants (specifies desired behavior) Represents a functional requirement on the system Use case involves interaction of actors and the system
Market Analysis

Financial Officer
Frank Maurer, University of Calgary 148

Use cases: terms and concepts


s s

Unique name Sequence of actions (event flows)


textual (informal, formal, semi fomal)
Main flow of events: The use case starts when the system prompts the Customer for a PIN number. The Customer can now enter a pin number...

interaction diagrams

Frank Maurer, University of Calgary

149

Actors
s

Role that a user plays with respect to the system Actors carry out use cases
look for actors, then their use cases

s s

Actors do not need to be humans! Actors can get value from the use case or participate in it
Frank Maurer, University of Calgary 150

Actors
s

Actors can be specialized

Officer
s s

connected to use cases only by association Financial Officer association = communication relationship (each one sending, or receiving messages)

Frank Maurer, University of Calgary

151

Use case description


s

s s

Generic, step-by-step written description of a use cases event flow Includes interactions between the actor(s) and a use case May contain extension points Clear, precise, short descriptions

Frank Maurer, University of Calgary

152

Example use case description


s

Capture deal 1. Enter the user name & bank account 2. Check that they are valid 3. Enter number of shares to buy & share ID 4. Determine price 5. Check limit 6. Send order to NYSE 7. Store confirmation number
Frank Maurer, University of Calgary 153

Organizing Use Cases


s s s

Generalization Use/Include Extend

Frank Maurer, University of Calgary

154

Generalization relationship
s

Validate user

Check password

Retinal scan

child use case inherits behavior and meaning of the parent use case child may add or override the parents behavior child may substitute any place the parent appears
155

Frank Maurer, University of Calgary

Extends relationship
s

Capture deal <<extend>>

s s

Allows to model the part of a use case the user may see as optional Allows to model conditional subflows Allows to insert subflows at a certain point, governed by actor interaction represented by an extend dependency extension points (in textual event flows)
Frank Maurer, University of Calgary 156

Limit exceeded

s s

Extends relationship
s s

Capture deal <<extends>>

Allows to model the part of a use case the user may see as optional Allows to model conditional subflows Allows to insert subflows at a certain point, governed by actor interaction Capture the base use case For every step ask
what could go wrong how might this work out differently

Limit exceeded

Plot every variation as an extension of the use case


Frank Maurer, University of Calgary 157

Example: extension points


s

Capture deal
1. Enter the user name & bank account 2. Check that they are valid extension point: reenter data in case they are invalid 3. Enter number of shares to buy & share ID 4. Determine price 5. Check limit 6. Send order to NYSE 7. Store confirmation number

Frank Maurer, University of Calgary

158

Uses/Includes relationship
s

Used to avoid describing the same flow of events several times, by putting the common behavior in a use case of its own
<<uses>> Analyze risks Valuation <<uses>

Price details

Avoids copy-and-paste of parts of use case descriptions


Frank Maurer, University of Calgary 159

Comparing extends/uses
s

Different intent
extends
to distinguish variants set of actors perform use case and all extensions actor is linked to base case

uses/includes
to extract common behavior often no actor associated with the common use case different actors for caller cases possible

Frank Maurer, University of Calgary

160

A use case diagram


<<uses>> Analyze risks Trader Valuation <<uses>

Price details

Sales system Capture deal <<extends>>

Limit exceeded
Frank Maurer, University of Calgary 161

Use Case Diagrams (Functional)

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

162

Properties of use cases


s s s

Granularity: fine or course Achieve a discrete goal Use cases describe externally required functionality Often: Capture user-visible function

Frank Maurer, University of Calgary

163

When and how


s s

Requirements capture - first thing to do Use case: Every discrete thing your customer wants to do with the system
give it a name describe it shortly (some paragraphs) add details later

Frank Maurer, University of Calgary

164

Class diagrams
s s s

Overview Class diagram essentials Generalization

Frank Maurer, University of Calgary

165

Class diagram
s s

Central for OO modeling Shows static structure of the system


Types of objects Relationships
Association Subtypes

Frank Maurer, University of Calgary

166

Perspectives
s

Conceptual
Shows concepts of the domain Independent of implementation

Specification
Interfaces of software (types) Often: Best perspective

Implementation
Structure of the implementation Most often used
Frank Maurer, University of Calgary 167

Class
s s

Set of objects Defines


name attributes operations

Task startDate endDate setStartDate (d : Date = default) setEndDate (d : Date = default) getDuration () : Date

Frank Maurer, University of Calgary

168

Class versus type


s

OO type = protocol understood by an object = set of methods that are implemented Class = implementation oriented construct
implements one or more types

Type: Used for specification


Frank Maurer, University of Calgary 169

Association
s

Relationship between instances of classes A student is registered for a course A professor is teaching the course

Frank Maurer, University of Calgary

170

Class diagram example


Actuator startUp( ) shutDown( )

Light off( ) on( ) *

Heater 1 1

Cooler

Temperature

1 1 Environmental Controller 1 Define_climate( ) Terminate_climate( )

SystemLog Display( ) RecordEvent( )

Frank Maurer, University of Calgary

171

Rules of thumb
One class can be part of several diagrams Diagrams shall illustrate specific aspects
Not too many classes Not too many associations Hide irrelevant attributes/operations

Several iterations needed to create diagram

Frank Maurer, University of Calgary

172

Class diagrams
s s s

Overview Class diagram essentials Generalization

Frank Maurer, University of Calgary

173

Association
s

Relationship between classes


Order dateReceived isPrepaid number : String price : Money dispatch( ) Customer name address 1 creditRating( )

hasCustomer *

Order comes from one customer Customer may make several orders
Frank Maurer, University of Calgary 174

Naming associations
s

Avoid meaningless names


associated_with has is_related_to

Name is often a verb phrase


has_part is_contained_in
Frank Maurer, University of Calgary 175

Roles
Order dateReceived isPrepaid number : String price : Money dispatch( ) 1

s s

s
line item * OrderLine quantity price isSatisfied

Association has two roles Role is a direction on the association Role


Explicit labeled Implicitly named after the target class

Frank Maurer, University of Calgary

176

Role names
s

Role = identifies one end of an association


Company Name Address employer Works for employee Person Name Insurance no. Address

Role name is obligatory for associations between objects of the same class
Manager
Person Name Insurance no. Address

Supervises

Salesperson
Frank Maurer, University of Calgary 177

Multiplicity
s

Indicates how many object can participate in the relationship


Order dateReceived isPrepaid number : String price : Money dispatch( ) Customer name address * 1 creditRating( )

Frank Maurer, University of Calgary

178

Multiplicity (2)
s s s s s

*: 0..infinity 1: 1..1 0..1 1..100 2,4,5

Frank Maurer, University of Calgary

179

Specification perspective
s

Association represents responsibilities


Order date Received isPrepaid number : String price : Money * 1 creditRating( ) Customer name address

Method in Customer returning Orders Method in Order that returns the Customer that made the order

Frank Maurer, University of Calgary

180

Navigability
s

Arrows indicate navigability


Order date Received isPrepaid number : String price : Money Customer name address * 1 creditRating( )

s s

Order has to be able to determine the Customer Customer does not know Orders Bi-directional association: Navigability in both directions (inverse roles)
Frank Maurer, University of Calgary 181

Summary: Basic notation for associations


Class B role_B Association name role_A Class B

Order

Contains made_up_of included_in

Part

Frank Maurer, University of Calgary

182

Naming conventions
Order dateReceived isPrepaid number : String price : Money dispatch( ) 1

Naming conventions allow often to infer the names of messages from the diagram class Order { public Enumeration orderLines(); public Customer customer(); }

line item

* OrderLine quantity price isSatisfied

Frank Maurer, University of Calgary

183

Example: Hockey statistics


Class

Frank Maurer, University of Calgary

184

Association classes
s

Useful if
attributes dont belong to any one class but to the association
User Authorized on Workstation

Authorization Priority Access rights Start session

Directory Frank Maurer, University of Calgary 185

Contents
s s s s s s

Attributes and operations Aggregation Inheritance Interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 186

Classes and objects


Task startDate : Date = 1.1.98 endDate : Date = 1.1.98 setStartDate (d : Date = default) setEndDate (d : Date = default)

Objects show
Object name Class name (optional) Attribute value (optional)

Assignment 1: Task startDate = 1.2.98 endDate = 23.2.98

Assignment 1: Task startDate = 1.2.98 endDate = 23.2.98

Assignment 1: Task startDate = 1.2.98 endDate = 23.2.98

Frank Maurer, University of Calgary

187

Example
Salesperson Generates Class diagram: curtisClyde: Order Includes CustInfo order121: ace furniture: Object diagrams: order122: harmon assoc:
Frank Maurer, University of Calgary

Contains

Line

line1: line2: line3: line4: line1: line2:


188

Attributes
s

Customer name address creditRating

Conceptual: Indicates that customer have names Specification: Customer can tell you his/her name and set it Implementation: An instance variable is available UML syntax:
<attribute name>: <Data type>

Frank Maurer, University of Calgary

189

Difference between attribute and association


s

Conceptual perspective
not much of a difference!

Specification/implementation perspective
Attribute stores values NOT references
no sharing of attribute values between instances!

Often: Stores simple objects


Numbers, Strings, Dates, Money objects

Frank Maurer, University of Calgary

190

Operations
s s s

Processes that can be carried out on instances Correspond to messages of the class Conceptual perspective principal responsibilities Specification perspective public messages = interface of the class Normally: Dont show operations that manipulate attributes

Frank Maurer, University of Calgary

191

UML syntax for operations


<visibility> <name> (<parameter list>) : <return-typeexpression> + assignAgent (a : Agent) : Boolean
visibility: public (+), protected (#), private (-)
Interpretation is language dependent Not needed on conceptual level

name: string parameter list: arguments (syntax as in attributes) return-type-expression: language-dependent specification

Frank Maurer, University of Calgary

192

Types of operations
s

s s s

Query = returns some value without modifying the class internal state Modifier = changes the internal state Queries can be executed in any order Getting & setting messages
getting: query setting: modifier
Frank Maurer, University of Calgary 193

Contents
s s s s s s

Attributes and operations Inheritance Aggregation Interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 194

Subclassing
s

Class inherits features from (more than) one superclass vehicle

land vehicle

water vehicle

car

amphibian vehicle

ship

Frank Maurer, University of Calgary

195

Subclassing
s

Attributes & operations of an ancestor class are inherited to the subclass Extension: adding of new attributes or operations Restriction: additional restrictions on ancestor attributes

Frank Maurer, University of Calgary

196

Perspectives
s s

Conceptual: Subset relationship Specification: Subtype conforms to supertype interface Implementation: Implementation inheritance, subclassing

Frank Maurer, University of Calgary

197

Contents
s s s s s s

Attributes and operations Inheritance Aggregation Interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 198

Aggregation
s s

Special form of association Components are parts of aggregated object


Car has an engine and wheels as its part

Typical example:
parts explosion organizational structure of a company

Frank Maurer, University of Calgary

199

Notation for aggregation


Class A
or

Class A Class B Class C

Class B

Class C

Frank Maurer, University of Calgary

200

Example: Aggregation
Compan y
works for

Unit

Department

Group

Person

Frank Maurer, University of Calgary

201

Aggregation and composition


s

Composition

Aggregation

Order
* 1

Components belong only to one Composition whole Parts live and die with the whole
cascading delete also needed for 1..1 associations The players can be aggregated to the Flames BUT they are not killed when the Flames disappear

Customer LineItem Adress

Frank Maurer, University of Calgary

202

Aggregation association
s s

Transitive Antisymmetric: Object may not be directly or indirectly part of itself

Frank Maurer, University of Calgary

203

Recursion
s

Directed path of aggregation associations from a class to itself Variable aggregation: finite number of levels, number of parts variable (example: company)

Frank Maurer, University of Calgary

204

Example: recursive aggregation


Class diagram: Object diagram:
a: Container Item b: Icon Icon Container d: Icon e: Icon c: Container

Frank Maurer, University of Calgary

205

Example: Recursive aggregation


Program

Class

Inner class

Frank Maurer, University of Calgary

206

Rules for using aggregation


s

s s s s

Distinction between association and aggregation often rather matter of taste than difference in semantics Aggregation IS association Aggregate is inherently sum of its parts Chains of aggregate links may not form cycles Composition is appropriate when each part is owned by one object, part has not have an independent life from its owner
Frank Maurer, University of Calgary 207

Chaining of operations
s

Chaining: Applying an operation to a net of objects Often for: copy, save, redo, delete, print
Document owns copy copy copy copy Paragraph copy Character

Person

Frank Maurer, University of Calgary

208

Delegation & aggregation


vehicle vehicle

land vehicle

water vehicle

LandFeature car amphibian vehicle ship

WaterFeature

VehicleFeature

Frank Maurer, University of Calgary

209

Most important feature & aggregation


vehicle

vehicle

land vehicle land vehicle big vehicle

car car train ship

train

Size Frank Maurer, University of Calgary 210

Generalization based on different dimensions


vehicle land vehicle

..

car

train

small car

big car

small train

big train

Frank Maurer, University of Calgary

211

Contents
s s s s s s

Attributes and operations Inheritance Aggregation Types, interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 212

OO types
s

Stereotype <<type>> specifies


domain of objects operations (not their implementation) applicable to the objects of this type
<<type>> Collection

Stereotype
<<implementation class>> physical data structures and methods of an object
<<type>> Set addElement(Object) removeElement(Object) testElement(Object) : Boolean <<implementation class>> HashTableSet element s : HashTable addElement (Object) remov eElement(Object ) tes tElement(Object) : Boolean setTableSize(Integer)

Frank Maurer, University of Calgary

213

Types and Roles


s

interfaces that belong to a class represent different roles You can explicitly state the role a class presents to another class:
<<interface>> Employee getEmploymentHistory() getCompensation() getBenefits() Person e: Employee 1..* * Company

Frank Maurer, University of Calgary

214

Static and dynamic types


s

Static types: the type of an object doesnt change over time, e.g. classes Dynamic types: object can gain and lose types during lifetime Example: Candidate, Employee, Retiree

Frank Maurer, University of Calgary

215

Abstract class
s s s s

has no instances organizes attributes & operations often: facilitates code reuse abstract operation: implementation in concrete subclasses can contain concrete implementations
Frank Maurer, University of Calgary 216

Abstract class in UML


s

Name in italic and/or {abstract} constraint

Windows Window Window Text Editor


{abstract} toFront() toBack() toFront() toBack()

X11 Window
toFront() toBack()

Mac Window Dependency


Frank Maurer, University of Calgary

toFront() toBack()
217

Interfaces in UML (1)


s s

Stereotype <<interface>> Lollipops


<<interface>>

InputStream
{abstract}

DataInput
Generalization

OrderReader
Dependency

DataInputStream

Realization

Frank Maurer, University of Calgary

218

Interfaces in UML (2)


DataInput OrderReader
Interface DataInputStream Dependency

InputStream
Frank Maurer, University of Calgary 219

Parameterized classes
s s

Parameterized class = template Often used for collections in typed languages

Not needed in conceptual modeling


Collections are hidden in multiplicity
T Set insert (newArg : T = default) remove (arg : T = default)

Frank Maurer, University of Calgary

220

Bound element
s

Using a parameterized class

Set
Template Class

insert(T) remove(T) <<bind>> <Employee> EmployeeSet


Binding for Parameter
221

Set <Employees>
Refinement

Bound Element

Frank Maurer, University of Calgary

Contents
s s s s s s

Attributes and operations Inheritance Aggregation Interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 222

Constraints
s

Basic constructs specify important constraints


but: can not capture everything

Additional constraints: in braces { } {UofC has always to be better than UofA} {immutable} {read only}
Frank Maurer, University of Calgary 223

Example
Chair-of 1 Person {subset} * Committee

* Member-of

Frank Maurer, University of Calgary

224

Collections for multi-valued roles


s

Multiplicity > 1
Set
no target object appears more than once not ordered

Add constraint to change that


{ordered} {ordered bag} {dag} Window {bag} {hierarchy}
{ordered} Visible on Screen

Frank Maurer, University of Calgary

225

Association classes
s

Useful if
attributes dont belong to any one class but to the association
User Authorized on Workstation

*
Authorization Priority Access rights Start session

Directory Frank Maurer, University of Calgary 226

Remodeling: association classes


User Authorization Workstation Priority Access rights Start session

Directory

Frank Maurer, University of Calgary

227

Qualified associations (1)


s

UML equivalent for Hashtable

o1 44 o2 56 Task ToDoList o3 87 name : String 0..1 o4Within a ToDoList, you mustnt have two tasks with the same name 99

class ToDoList { public Task getTask(String name); public void addTask(String name, Task aTask); }

Multiplicity *: Multiple task with one name

Frank Maurer, University of Calgary

228

Qualified association (2)


s s

Improves semantic accuracy Makes navigation paths understandable


Stock exchange Stock exchange
StockID noted *

not qualified

qualified
noted

Company StockID

Company

Frank Maurer, University of Calgary

229

Qualified association (3)


s

Qualification splits a set of objects in disjunctive parts


Company Function
Organization

Person

ABC Inc. ABC Inc. ABC Inc. ABC Inc. ABC Inc. XYZ Inc.

President Vice President Finances Member of board Member of board Member of board President

Roger Rabbit Joe Savemoney John Walker Susi Sanssouci Karl Eichbaum Donald Duck

Frank Maurer, University of Calgary

230

Derived associations and attributes (1)


s s

Calculated based on other attributes and associations Specification: Shows constraint not what is stored and what is calculated

Frank Maurer, University of Calgary

231

components {hierarchy}

Derived associations and attributes (2)


* Account
/balance:Money / entries

Entry
amount:Money

Derived Attribute

Derived Role

Summary 0..1 Account


Entries role is derived using components.entries

Detail Account
Note

Frank Maurer, University of Calgary

232

Class Diagram (Structural)


s

Use: Describe the static structure of a system


Hierarchy Containment Inheritance Calling Object Types
Frank Maurer, University of Calgary 233

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Contents
s s s s s s

Attributes and operations Inheritance Aggregation Interfaces and abstract classes Advanced association concepts When and how
Frank Maurer, University of Calgary 234

When to use class diagrams


s

Class diagrams are the backbone of OO development approaches Dont use all the notations
start with simple stuff

Take the perspective into account


not to many details in analysis specification often better than implementation

Concentrate on key areas


better few up-to-date diagrams than many obsolete models
Frank Maurer, University of Calgary 235

Creating a class diagram


s

Start simple
major classes & obvious associations

Then add
Attributes Multiplicity Operations

Frank Maurer, University of Calgary

236

Rules of thumb
One class can be part of several diagrams Diagrams shall illustrate specific aspects
Not too many classes Not too many associations Hide irrelevant attributes/operations

Several iterations needed to create diagram

Frank Maurer, University of Calgary

237

Avoid Heavy classes


s s

Controller does everything A Other classes: Data encapsulation only


D HeavyControler doIt( )

B C

Frank Maurer, University of Calgary

238

Contents
s s

State diagrams: an example Interaction diagrams


Sequence diagrams Collaboration diagrams

Frank Maurer, University of Calgary

239

Example
s s s s

s s s s

A zoo consists of a set of cages. Every cage is the home of at least 2 animals. Cages are located besides each other. Every cage has at most one left neighbor and at most one right neighbor. Animals can be reptiles, insects, and mammals. Mammals are elephants, monkeys, and tigers. Monkeys eat bananas. Tigers prefer meat.
Frank Maurer, University of Calgary 240

Traffic lights
s

Develop a state transition diagram for the 4 traffic lights at a crossing. Make sure that the lights never allow traffic to move east to west (or west to east) at the same time as they allow traffic to move north to south (or south to north). Give meaningful names to all state transitions.

Frank Maurer, University of Calgary

241

Contents
s s

State diagrams: an example Interaction diagrams


Sequence diagrams Collaboration diagrams

Frank Maurer, University of Calgary

242

Interaction diagrams
s s

describe how groups of objects interact typically describe the scenario of a single use case show
example objects messages between them timeline

Frank Maurer, University of Calgary

243

Sequence diagrams
s

shows object interactions arranged in time sequence


objects (and classes) message exchange to carry out the scenarios functionality

time line

Frank Maurer, University of Calgary

244

Objects in UML
s s

Rectangle Name (specific or general) of object is underlined


name name & class class (anonymous object)

Object Name History 101-Section 2 Object Name and Class History 101-Section 7: CourseOffering Class Name : CourseOffering
Frank Maurer, University of Calgary 245

Timelines
s

Messages point from client to supplier


: Professor CourseManager Math 101 - Section 1 : CourseOffering

Add professor (Professor)

Frank Maurer, University of Calgary

246

Example: Sequence diagram


: Registrar theManager : course form : CourseForm CurriculumManager aCourse : Course

1 : set course info 2 : process 3 : add course 4 : new course

Frank Maurer, University of Calgary

247

Sequence diagrams: More details


Iteration
an Order Entry window 1: prepare() an Order 2: * prepare()

Object creation

Condition
a Stock Item

an Order Line

3: check() 5: needsToReorder()

4: [check = true] remove()

Asynchronous Message

Activation

Self Object deletion delegation


248

Frank Maurer, University of Calgary

Asynchronous messages
s s

Do not block the caller Can do 3 things:


Create a new thread Create a new object Communicate with a thread that is already running

Frank Maurer, University of Calgary

249

Boundary classes
s

Handle communication between system and outside world


e.g. user interface or other system

Boundary classes in interaction diagrams:


capture interface requirements do NOT show how the interface will be implemented
Frank Maurer, University of Calgary 250

Complexity and sequence diagrams


s

KISS = keep it small and simple Diagrams are meant to make things clear Conditional logic
simple: add it to the diagram complex: draw separate diagrams
Frank Maurer, University of Calgary 251

Contents
s s

State diagrams: an example Interaction diagrams


Sequence diagrams Collaboration diagrams

Frank Maurer, University of Calgary

252

Sequence Diagram (Behavioral)


s

Use: Describing behavior across several objects of a use-case or scenario


Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

253

Sequence Diagram with Concurrency

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

254

Collaboration diagrams
s s

Show objects and messages Sequence of messages determined by numbering


1, 2, 3, 4, .. 1, 1.1, 1.2, 1.3, 2, 2.1, 2.1.1, 2.2, 3 (shows which operation calls which other operation)
Frank Maurer, University of Calgary 255

Collaboration diagram basics


: ProfessorCourseManager 1 : Add professor (Professor)

Math 101 - Section 1 : CourseOffering

Frank Maurer, University of Calgary

256

Collaboration diagram example


1 : set course info 2 : process

course form : CourseForm

: Registrar

3 : add course

aCourse : Course

theManager : CurriculumManager
4 : new course

Frank Maurer, University of Calgary

257

Collaboration Diagram (Behavioral)


s

Use: Describing behavior across several objects of a use-case or scenario


Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

258

Comparing sequence & collaboration diagrams


s

Sequence of messages more difficult to understand in collaboration diagrams Layout of collaboration diagrams may show static connections of objects Complex control is difficult to express

Frank Maurer, University of Calgary

259

State diagrams
s s

Design document State diagrams

Frank Maurer, University of Calgary

260

Main processes of the team assignment


requirements analysis
problem description requirements document

design process

coding

testing

design document

Used technique: Use cases

Used technique: UML class diagrams, UML sequence diagrams, UML activity diagrams UML state diagrams

Used language: Java

Frank Maurer, University of Calgary

261

Refined design processes of the team assignment


requirements analysis design process coding testing

create system architecture

specify component develop interfaces component design


Techniques: UML class diagrams, UML sequence diagrams, UML state diagrams
Frank Maurer, University of Calgary 262

Design document
s s

System architecture: class diagrams Component interfaces


class diagrams (interfaces, types) sequence diagrams

Component design
class diagrams state diagrams sequence diagrams
Frank Maurer, University of Calgary 263

Design document - aim


s s

Basis for implementation provides different views


other developers: architecture, component interfaces implementation: straightforward

Allows quick overview over the system structure and main design decisions Allows developers to work in parallel

Frank Maurer, University of Calgary

264

Diagram notations
s

State diagrams
describe the behavior of objects

Activity diagrams
describe the flow of work parallel processing

Sequence diagrams
describe time ordering of messages

Deployment diagrams
physical relationship of software and hardware
Frank Maurer, University of Calgary 265

State diagrams
s s

Design document State diagrams

Frank Maurer, University of Calgary

266

State diagrams
s

State diagram: Shows the behavior of one object


how does it change its state based on the messages it receives narrowly focused, fine-grained

Other names
State transition diagram Harel diagram (statecharts)

Frank Maurer, University of Calgary

267

State diagrams (2)


deposit

Over drafted

s
withdraw

State: condition/situation during lifetime of an object State transition: relationship indicating a state change
atomic & non-interruptible

withdraw deposit ok

Action:
atomic & non-interruptible

Frank Maurer, University of Calgary

268

State notation (1)


s s
State name state variable(s) entry: entry action do: activity-A on: event-A: action-A exit: exit-action

Substates: disjoint/concurrent Entry/exit actions


entry: an action that is performed on entry to the state exit: an action performed on exiting the state

do: an ongoing activity performed while in the state (example: display window)
interruptible

on: an action performed as a result of a specific event


269

Frank Maurer, University of Calgary

Transition notation (2)


State-A
Event(arguments)[condition]/action

State-B

Event: significant occurrence that has a location in time and space


triggers the transition signals, calls, passing of time, change in state

Guard condition:
Transition only eligible to fire when guard evaluates to true Guards of transition exiting one state are mutually exclusive

Action: executable atomic computation


Frank Maurer, University of Calgary 270

State diagram notation (3)


Initial state Event(attribute) State-B

Start state
No event triggers allowed branch conditions allowed may not remain in start states

End state
Top level end state terminates a state machine
Frank Maurer, University of Calgary 271

State transitions for an order


get next item[ not all items checked ] Item received[ some items not in stock ] [ All items checked && some items not in stock ]

/ get first item

Checking do: check item

Waiting

[ All items checked && all items available ]

Item received[ all items available ]

Dispatching do: initiate delivery

Delivered

Delivered

Frank Maurer, University of Calgary

272

State Diagram (Behavioral)


s

Use: Describing behavior of a single object Hint: the entire system is a single top-level object

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

273

States of a hockey game


shootout tie[ time is up ] playing Boxing penalty face off win[ time is uo ] break end of game

Frank Maurer, University of Calgary

274

Problem: Cancel the order


s

Want to be able to cancel an order at any time Solutions


Transitions from every state to state cancelled Superstate and single transition

Frank Maurer, University of Calgary

275

Transitions to cancelled
get next item[ not all items checked ] Item received[ some items not in stock ] / get first item Checking do: check item [ All items checked && some items not in stock ] Waiting

[ All items checked && all items available ]

Item received[ all items available ] cancelled cancelled

Dispatching do: initiate delivery

cancelled Cancelled

Delivered

Delivered

Frank Maurer, University of Calgary

276

State diagram notation (4)


Superstate Event A

State-A

State-B

Event B

Event C

Frank Maurer, University of Calgary

277

State Diagram with Substates

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

278

Superstate
Active get next item[ not all items checked ] Item received[ some items not in stock ]

/ get first item

Checking do: check item

[ All items checked && some items not in stock ] Waiting

cancelled

Cancelled

[ All items checked && all items available ]

Item received[ all items available ]

Dispatching do: initiate delivery

Delivered Delivered

Frank Maurer, University of Calgary

279

Hockey example with superstate


Normal tie[ time is up ] playing shootout

penalty face off win[ time is uo ]

Boxing

break

end of game

Frank Maurer, University of Calgary

280

Some remarks
s

Only one initial state may occur (directly) within a composite state End state represents completion of a composite End state triggers transition with composite as source

Frank Maurer, University of Calgary

281

Orthogonal components and concurrency


s s

Unrelated components of objects combinatorial number of states 4 car states: Example: Car states What happens when we add one
seat belt (fastened, open)
8 car states: started_open_open started_closed_open stopped_open_open stopped_closed_open

engine (started, stopped) doors (open, closed)

started_open started_closed stopped_open stopped_closed component?

started_open_fastened started_closed_fastened stopped_open_fastened stopped_closed_fastened


282

Frank Maurer, University of Calgary

Example: Payment authorization in class Order


Authorizing do: check payment [ payment not ok ]

2 parallel processes: - authorization - order handling

[ payment ok ] Authorized Rejected

Delivered

Frank Maurer, University of Calgary

283

Concurrent state diagram for the class Order


Cancelled Waiting Checking Dispatching Delivered

Authorizing

Authorized

Rejected

Frank Maurer, University of Calgary

284

State Diagram with Concurrency

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

285

Rules of thumb
s s s

Not every class needs a state diagram Often: State diagram not very complex State diagrams are often used for UI and control objects Not to many concurrent sets of behavior occurring in a single object (in that case: split into separate objects)
Frank Maurer, University of Calgary 286

Activity Diagrams (Behavioral)


s s s s

Use: Understanding Work-Flow Use: Analyzing UseCase Use: Dealing with MultiThreading No: Analyzing Object Collaboration
Use Sequence or Collaboration Diagrams

No: Analyzing Object Behavior


Use State Diagram
Frank Maurer, University of Calgary
Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

287

Activity Diagrams with Swim Lanes

Frank Maurer, University of Calgary


Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

288

Package Diagram (Structural)


s

Use: LargeProject Structures

Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

Frank Maurer, University of Calgary

289

Deployment Diagram
s

Use: Describing System/Hardwar e/Software Relationships

Frank Maurer, University of Calgary


Diagram: UML Distilled, Martin Fowler, Kendall Scott, 1997, Addison-Wesley, Copyright 1997, Addison-Wesley

290

Vous aimerez peut-être aussi