Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 1 -
Object Oriented System Development Lecture 7
Classes, Objects and Relations,
State Chart, OAL
Rogardt Heldal
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 2 -
Obtaining operations
p2:Point
p1:Point
: Line move(p3)
2 Line
move(dist:Point):void
Point
x:double
y:double
move(dist:Point):void
1
Line
Point
X:double
Y:double
1 2
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 3 -
Mapping to code • One can map a UML class to many different code skeletons in
different programming languages such as:
• In the previous lecture we showed a mapping to Java
• The focus of UML has mainly been on specifying software system gap between models and code can lead to inconsistency.
Point
x:double
y:double
move(dist:Point):void
Java
C#
C++
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 4 -
BridgePoint • BridgePoint supports a subset of UML.
• BridgePoint strength is that the model can be executed.
• Model can be executed and tested!
• Model compilers take Models to code such as C, C++, C#, Java etc. BridgePoint comes with a compiler to C.
• No gap between models and code.
• Focus in this lecture is on UML 2, but we will also see BridgePoint relationship to UML 2.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 5 -
Executable Model Hierarchy
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 6 -
Relationship between Model Elements
• Executable, tightly coupled: – Component
– Class
– State
– Action
• Informal, loosely coupled – Use Case
– Sequence*
– Communication*
– Activity
• Package
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 7 -
UML Classes: Visibility
Point
- x:double
- y:double
+ move(dist:Point):void
Mapping visibility to java: • - -> private • # -> protected • + -> public • ~ -> package
(In this case the semantics of -,#,+,~ will be the one of Java.)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 8 -
UML attribute
UML: [visibility] name [multiplicity] [:type] [= initial value]
[{properties}]
Properties could be: – changeable (Variable may be changed.) – addOnly (When multiplicity is bigger than one you can add more
values, but not change or remove values.) – frozen (Cannot be changed after it has been initialized.)
• Example:
– x : int {frozen}
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 9 -
Operations/methods
UML: [visibility] name [(parameter list)] [: return type] [{properties}]
You can have zero or more parameters. Syntax for parameters:
[direction] name : type [= default value] – direction: in, out, inout
• Example of a property – isQuery (no ”side effects”)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 10 -
Relations
• All the associations we consider when drawing domain models can also be used in class diagrams.
• But there are some interesting issues to consider …
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 11 -
Navigability
Point Line 1 2
Line knows Point,
but Point doesn‟t know
Line.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 12 -
Association constraint
Constraint: • changeable (Links may be changed.) • addOnly (New links can be added by an object on the opposite
side of the association.) • frozen (When new links have been added from an object on
the opposite side of the association, they cannot be changed.) • ordered (Has a certain order) • bag (multisets instead of sets) • …
Company Person
{ordered}
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 13 -
Class diagram elements in BridgePoint Class name
Attributes {
Association label
Verb phrase
Multiplicity, Conditionality
Tags: Class number Keyletters
BridgePoint do
not contain visibility
and properties
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 14 -
Association names UML
Person Company * * employees employers
works for
Association name, Verb phrase
Role name,
Noun phrase
UML:
Person works for company
Can be read only one way
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 15 -
Association names BridgePoint
Employee Company * * has currently works for
R1
Association label
Verb phrase
BridgePoint:
•Association label plays a key role in BridgePoint.
•It is used in the OAL Object Action Language (see later slides).
• To create link between objects (link is an instance of an association)
• To obtain objects over links
•BridgePoint generates automatically the association label.
Employee work for company
Company has currently employees
Can be read in both direction
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 16 -
BridgePoint:tag
Bok {1,Bok}
Tags: Class number Keyletters
Class number is produced automatically by BridgePoint. As far as
I know we don‟t need to consider class numbers for the project.
A key letter will also be produced automatically, but this one you should
change to the same name as the class name!
• Keyletters is used in OAL
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 17 -
Association Class
Company Person * *
Job
salary
Can be modeled in BridgePoint.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 18 -
Class methods and class variables
Account
-interestRate:double
-balance:double
+changeInterestRate(newinterestrate:double)
BridgePoint has support for class-based operations. Class-based
attributes has been on its way for some time, but is not supported yet.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 19 -
Class templates
Stack
+ empty():Boolean{isQuery}
+ push(e:T):Void
+ pop():T
- n: int
- s : T[size]
T
size:int
PersonStack
<<bind>>(Customer,10)
Stack<Person,10>
Not part of BridgePoint.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 20 -
Interface
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 21 -
Interfaces
• Interfaces are very important. By using an interface you can separate implementation from specification.
• An interface specifies a service of a class
or component.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 22 -
Interfaces in UML
<<interface>>
AudioPlayer
play()
stop()
pause()
skipForward()
skipBackwards()
interface
DiscPlayer
In this lecture we will just look at interfaces connected to classes, but later we will also look at interfaces connected to components.
realization
MultiMedia
dependency
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 23 -
The same interface
Here TapePlayer is a new implementation of AudioPlayer. If you have done everything correctly you only have to change the implementation of the methods in the interface, the rest of the program remains the same. The MultiMedia doesn‟t need to be changed!
TapePlayer
MultiMedia
<<interface>>
AudioPlayer
play()
stop()
pause()
skipForward()
skipBackwards()
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 24 -
Dependency
DiscPlayer
MultiMedia
dependency
The class MultiMedia uses the methods in the interface, which are implemented by DiscPlayer.
DiscPlayer AudioPlayer
MultiMedia
dependency
realization <<interface>>
AudioPlayer
play()
stop()
pause()
skipForward()
skipBackwards()
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 25 -
Interface Specifiers <<interface>>
IEmployer
getCompensation()
getBenefits()
Person Company - employer:IEmployer
1..* 1
A person can have many other roles, such as customer, boss, father, pilot etc.
Roles can be shown using interfaces.
Person - supervisor:IManager
- worker:IEmployee 1 *
- employees
works for
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 26 -
Interface in BridgePoint • One does not model interfaces in the class diagram in
BridgePoint, but one models them when considering components (We will come back to components in a later lecture).
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 27 -
Inheritance
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 28 -
Example: Dwelling-house
DwellingHouse
#additionalInsulation:boolean
+ insulate()
super class
sub class
Inheritance
House
#length:double
#width:double
#numberOfFloors:int
#lastRenovation:int
+ area():double
# : visible with class and
in subclasses
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 29 -
Instances
Sometimes you want to work with instances of House and sometimes with instances of DwellingHouse etc.
length = 20
width = 15
numberOfFloors = 2
:House
length = 30
width = 20
numberOfFloors = 3
additionalInsulation = true
:DwellingHouse
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 30 -
leaf: stops inheritance public final class A { … } Note that also a method can be final. Then the method must not be
changed in the sub classes, e.g. public final int test (int x) { … }
A
{leaf}
B Not allowed!
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 31 -
Multiple inheritance
• This is allowed in C++, but not in Java. (But: For interfaces in Java multiple inheritance is allowed)
• There are limitations on the use of the use of inheritance in BridgePoint. Staffan will come back to these points next week.
PrivateCar MotorBoat
AmphibiousCar
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 32 -
xt-UML • xt-UML includes an action language OAL (Object Action
Language) to provide semantics to models.
• xt-UML is augmented with OAL.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 33 -
Case study • Now, we will show how to augment operations to obtain an
executable model
• You should learn this language by reading the OAL reference document found in the tool BridgePoint under the menu Help/Help Contents/BridgePoint UML Suite Help/ Reference/OAL Reference
• It is not a large document and you should be able to read it before the lecture on Thursday
• You will get more out of the lecture on Thursday if you read this document
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 34 -
A small case study Library
xt-UML
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 35 -
Book
ISBN
title
author
Exemplar *
exemplars
1
Lending
startDate
lendingPeriod
actualReturnDate
Borrower
name
SSNr
borrowId
* lendings
1
runningLending
0..1 0..1
AdmLib
addBorrower(name,SSNr)
isMember(SSNr)
addBook(ISBN,title,authore)
addExemplar(ISBN,
exemplarId,place)
searchExemplar(exemplarId)
borrowExemplar(SSNr,
exemplarId)
getBorrower(SSNr)
…
*
0..1
allBorrower
lentExemplar
allBooks
allE
xem
pla
r
exemplarId
place
id2
addExemplar(exemplarId,
place)
*
*
R1
R5
R6
R2 R4
R3
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 36 -
addBorrower(name,SSNr) create object instance borrower of Borrower;
borrower.Borrower(name:param.name,SSNr:param.SSNr);
relate self to borrower across R1;
Borrower contains this method:
Borrower(name,SSNr) self.name = param.name;
self.SSNr = param.SSNr;
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 37 -
isMember(SSNr)
select any borrower related by self -> Borrower [R1]
where selected.SSNr == param.SSNr;
return(not empty borrower);
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 38 -
addBook(ISBN,title,author) create object instance book of Book;
book.Book(ISBN:param.ISBN,title:param.title,author:param.author);
relate self to book across R5;
Book contains this method:
Book(ISBN,title,author)self.ISBN = param.ISBN;
self.title = param.title;
self.author = param.author
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 39 -
addExemplar(ISBN,exemplarId,place)
select any book related by self -> Book [R5]
where selected.ISBN == param.ISBN;
book.addExemplar(exemplarId:param.exemplarId,
place:param.place);
select any exemplar from instances of Exemplar
where (selected.exemplarId == param.exemplarId);
relate self to exemplar across R6;
To obtain an object, using links should be avoided as much
as possible. It is not very object oriented.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 40 -
SearchExemplar(exemplarId)
select any exemplar related by self -> Exemplar[R6]
where (selected.exemplarId == param.exemplarId);
select any bookHelper from instances of BookHelper;
if not empty exemplar
return exemplar.id2;
else
return bookHelper.NoBook;
end if; BookHelper
NoBook
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 41 -
getBorrower(SSNr) select any borrower related by self -> Borrower [R1]
where selected.SSNr == param.SSNr;
if(not (empty borrower))
return borrower.borrowId;
end if;
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 42 -
borrowExemplar(SSNr,exemplarId)
if (self.isMember(SSNr:param.SSNr))
borrower_ref = self.getBorrower(SSNr:param.SSNr);
select any borrower from instances of Borrower
where selected.borrowId == borrower_ref;
ex_ref = self.searchExemplar(exemplarId:param.exemplarId);
select any help from instances of BookHelper;
if not(ex_ref == help.NoBook)
select any exemplar from instances of Exemplar
where selected.id2 == ex_ref;
create object instance lending of Lending;
lending.Lending(startDate:TIM::current_date(),lendingPeriod:30);
relate lending to exemplar across R3;
relate borrower to lending across R2;
relate self to borrower across R1;
end if;
end if;
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 43 -
Book(ISBN,title,author)
self.ISBN = param.ISBN;
self.title = param.title;
self.author = param.author;
addExemplar(exemplarId,place)
create object instance exemplar of Exemplar;
exemplar.Exemplar(exemplarId:param.exemplarId,
place:param.place);
relate self to exemplar across R4;
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 44 -
Borrower(name,SSNr) self.name = param.name;
self.SSNr = param.SSNr;
Exemplar(exemplarId,place) self.exemplarId = param.exemplarId;
self.place = param.place;
Lending(startDate,lendingPeriod) self.startDate = param.startDate;
self.lendingPeriod = param.lendingPeriod;
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 45 -
State Charts
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 46 -
State Charts for Objects
• Describe the set of states an object can be in, and the transitions between states which can happen.
• State charts can be used when you e.g. want to model the whole life cycle of an object.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 47 -
Syntax
transition
• A transition is a directed relationship between a source vertex and
a target vertex. A vertex can be a state, final state, or a
pseudostate.
• <transition> ::= <trigger> [„,‟trigger][„[„guarded-constraint„]‟]
[„/‟action]
State name
initial state
final state
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 48 -
Example: Library
Return an a copy of
a book.
Borrow a copy
of a book.
Borrower
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 49 -
CRC
Book
Responsibility Collaboration
Maintain data for a book. Know if there is
a copy to borrow.
Copy
Responsibility Collaboration
Maintain data for a certain copy of a book.
Inform corresponding book when the copy
is borrowed and returned.
Book
Library Member
Responsibility Collaboration
Maintain data about borrowed book copies.
Handle requests to borrow and return book
copies.
Copy
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 50 -
Collaboration
borrow(aCopy) 1:okToBorrow()
:Book
:LibraryMember
aCopy:Copy
2:borrow()
2.1 borrowed(aCopy)
return(aCopy)
:Book
:LibraryMember
aCopy:Copy
1:return()
1.1 returned(aCopy)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 51 -
Class Diagram
Book
returned(c:Copy)
borrowed(c:Copy)
book 1
*
Copy
return()
borrow()
-status:enum{OnShelf,Borrowed}
-status:enum{CanBeBorrowed,CanNotBeBorrowed}
copies
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 52 -
Copy: State Chart
Borrowed
On the shelf
return()
borrow()
initial state state
event
Copy
Responsibility Collaboration
Maintain data for a certain copy of a book.
Inform corresponding book when the copy
is borrowed and returned.
Book
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 53 -
Actions
Book
Copy
State chart for Copy:
Borrowed On the shelf
return()/book.returned(self)
borrow()/book.borrowed(self)
initial state
returned(c:Copy)
borrowed(c:Copy)
book
1 *
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 54 -
Conditions
Cannot be borrowed Can be borrowed
returned(copy)
borrowed(copy)
[copies->forall(
oclInState(Borrowed))]
returned(copy)
borrowed(copy)
[copies->exist(
oclInState(OnShelf))]
condition
State chart for Book:
Book
Responsibility Collaboration
Maintain data for a book. Know if there is
a copy to borrow.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 55 -
Problem: Set the time of a watch
• Pressing the “mode”-button of the watch will raise the event “modeButton”
• Pressing button “inc” of the watch will raise the event “inc”
• The call event modeButton is used to go between states, and the call event inc is used to increment hours in state SetHours and minutes in state SetMinutes.
• Problem: Draw the state chart diagram.
DigitalWatch
+modeButton()
+inc()
-state: enum{Display,SetHours,SetMinutes}
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 56 -
Solution: DigitalWatch
Display SetHours SetMinutes
modeButton()
modeButton() modeButton()
inc() inc()
state event
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 57 -
More Info: DigitalWatch
Display SetHours SetMinutes
do/display
current time
do/display
hours
do/display
minutes
modeButton()
modeButton() modeButton()
inc()/hours:=
hours+1 modulo 24
inc()/minutes:=
minutes+1 modulo 60
DigitalWatch
modeButton() inc()
state
activity
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 58 -
Compartments • Simple state chart describing how a password entry widget
works:
Enter Password
entry / set echo invisible
exit / set echo normal
do / blink cursor
character / handle character
help / display help
Name compartment
Internal activities
compartment,
contain also actions
Internal transition
compartment
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 59 -
Internal Actions
Borrowed
entry/book.
borrowed(self)
On the shelf
entry/book.
returned(self)
return()
borrow()
Borrowed
exit/book.
returned(self)
On the shelf
exit/book.
borrowed(self)
return()
borrow()
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 60 -
Internal Events
Working on Document
entry/open document
exit/close document
Working on Document
entry/open document
exit/close document
modify/commit modification
modify/commit modification
Internal event. Does not
cause “entry” or “exit”.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 61 -
Events • Call events
– All examples so far have been call events
• Time events
• Change events
• Signal events
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 62 -
Time Event
On
first floor
Moving up
do/moving
to floor
Idle, not first fl.
Moving down
do/moving to
floor
arrived
arrived [floor>1]
go down(floor)
go up(floor)
after(20 sec)/go down(1)
go up(floor)
Time event
arrived [floor=1]
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 63 -
Change event
On
first floor
Moving up
do/moving
to floor
Idle not first fl.
do/increase
timer
Moving down
do/moving to
floor
arrived
arrived[floor>1]
go down(floor)
go up(floor)
timer = timer-out /go down(first floor)
go up(floor)
Change event
arrived [floor=1]
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 64 -
Signal
<<signal>>
RejectedWithDrawal
date:Date
accountNumber:String
requestAmount:double
availableBalnace:double
Some of the following examples are taken from:
UML 2 and The Unified Process
Arlow and Neustadt
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 65 -
Signal events(1)
InCredit
deposit(m)/balance=balance+m
balance>=10000/notifyManager()
RejectingWithdrawal
entry/ logRejectedWithdrawal() AcceptingWithdrawal
entry/ balance=balance-m
withdraw(m)
[balance >= m]
withdraw(m)
[balance < m]
RejectedWithdrawal
close()
SimpleBankAccount
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 66 -
Signal events(2)
processRejectedWitdrawal(a:RejectedWithdrawal)
Calling customer
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 67 -
Connection transition
OnLoan Terminated
Overdue FineDue
after(
maximumDuration)
returnBook
[!extended]
returnBook
[extended]
loan
payFine
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 68 -
Branching Transitions
Unpaid
OverPaid FullyPaid PartiallyPaid makeRefund
[payment<balance]
[payment=balance]
[payment>balance]
acceptPayment
BankLoan
acceptPayment
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 69 -
Composite states
Accepted
Under treatment
Pre-treatment
Post-treatment
accept patient
treat patient
Surgery
incoming call/defer
Pay bill
Hospital
interrupt
Suspended treatment
restart
treatment
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 70 -
Shallow history
Accepted
Under treatment
Pre-treatment
Post-treatment
accept patient
treat patient
Surgery
incoming call/defer
Pay bill
Hospital
interrupt
Suspended treatment
continue
treatment
H
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 71 -
States with Substates
State1 State2 Staten a b c
State1 State2 Staten b c
finish finish finish
finish
Can be written as:
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 72 -
Composite State
• If region one finishes, then that region will terminate, but region two will continue to execute.
• In this case, if region one terminates first, the whole composite state will stop executing.
Region 1
Region 2
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 73 -
Example
Exercise 1 Exercise 2 exercise done exercise done
Term Project project done
exam pass
Failed
Studying
CourseAttempt
fail
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 74 -
Constructing State Machines
Draw and name the states you know.
Write a comment: what does this state mean?
Draw the transitions you know, into or out of each state.
Do incomplete transitions suggest missing states?
Define and name the known events.
Assign an event to each transition; any missing events?
Do events need to carry event data?
Check for completeness; add discovered states/transitions.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 75 -
BridgePoint statchart • To make BridgePoint state charts executable they have been
simplified, so a state only contains:
• <transition> ::= <trigger> [„/‟action]
• Both in entry and on transition one can use the OAL. You will see example on this on Thursday.
State name
entry / action
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 76 -
Checking for completeness
An automatic garage door: two buttons – up & down – and position sensors
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 77 -
Filling the State Transition Table
States
Events Entry Action
What do the empty cells mean?
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 78 -
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 79 -
A note on initial and final states • When an instance of a class is synchronously created, it
is placed in its initial state – It has not 'transitioned' into that state – so the
'entry' state action is not executed – An event assigned to a 'reflexive' transition can
trigger execution of the action – The initial state is the lowest numbered state
• A state machine may have one or more states with no outgoing transitions
– Obviously, when such a state is entered, the lifecycle can never proceed further
– The state can be marked as 'final„: after completing the state action, the instance will delete itself.
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 80 -
Comments • Most of the slides in this lecture is produce by me, but some
slides is borrowed from Mentor Graphics and the book “UML 2 and The Unified Process” (Arlow and Neustadt)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 81 -
Appendix
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 82 -
Withdraw Money Only main flow:
• user identifies himself by a card
• system reads the bank ID and account number from card and validates them
• user authenticates by PIN
• system validates that PIN is correct
• user requests withdrawal of an amount of money
• system checks that the account balance is high enough
• system subtracts the requested amount of money from account balance
• system returns card and dispenses cash
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 83 -
Alternative Flow
8-10a: Not enough money on account: 1. System does not change the account
2. System returns card
…
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 84 -
System Sequence Diagram Withdraw Money
insertCard(card)
givePin(userPin1)
giveAmount(amount)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 85 -
State Chart for Withdraw
CardInserted
gotCardPin
gotWrongPinOnce
gotWrongPinTwice
gotWrongPinThrice
gotRightPin
/cardPin=card.getPin()
givePin(userPin1)
[userPin1=cardPin]
givePin(userPin1)
[userPin1<>cardPin]
givePin(userPin2)
[userPin2=cardPin]
givePin(userPin2)
[userPin2<>cardPin]
givePin(userPin3)
[userPin3<>cardPin] givePin(userPin3)
[userPin3=cardPin]
/complain,keep card
giveAmount
(amount)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 86 -
Continue giveAmount
(amount)
gotRequestedAmount
gotCustomerID
gotBalance
finishedTransaction
insufficentBalance
/id:=card.getID()
/balance:=getBalance(id)
sufficientBalance
[balance>=amount]
Debit(id,amount)
/giveOutCash(amount)
/notifyInsufientBalance()
/retunrCard()
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 87 -
State Charts
Bottle
capacity:Integer
contents:Integer
fill(amount:Integer)
Cap 0..1 0..1
empty partiallyFilled
filled
capped
fill(amount:Integer)
[amount<capacity]
fill(amount:Integer)
[contents+amount<capacity]
fill(amount:Integer)
[contents+amount>=capacity]
fill(amount:Integer)
[amount>=capacity]
[contents = capacity]
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 88 -
empty partiallyFilled
filled
capped
fill(amount:Integer)
[amount<capacity]
fill(amount:Integer)
[contents+amount<capacity]
fill(amount:Integer)
[contents+amount>=capacity] fill(amount:Integer)
[amount>=capacity]
contents = capacity
Making Contract context Bottle::fill(amount:Integer)
pre: not filled and not capped
post: (partiallyFilled and
content@pre + amount < capacity)
or
(filled and contents@pre + amount >= capacity)
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 89 -
Code: DigitalWatch
Display SetHours SetMinutes
do/display
current time
do/display
hours
do/display
minutes
modeButton()
modeButton() modeButton()
inc()/hours:=
hours+1 modulo 24
inc()/minutes:=
minutes+1 modulo 60
DigitalWatch
modeButton() inc()
state
activity
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 90 -
State
public class State{
public final int Display = 1;
public final int SetHours = 2;
public final int SetMinutes = 3;
public int value;
}
DigitalWatch
+ modeButton()
+ inc()
State
+ Display : int = 1 {frozen}
+ SetHours : int = 2 {frozen}
+ SetMinutes : int = 3 {frozen}
+ value : int
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 91 -
public class DigitalWatch{
private State state = new State();
private DigitalDisplay LCD = new DigitalDisplay();
public DigitalWatch(){
state.value = state.Display;
LCD.displayTime();
}
public void modeButton() { … }
public void inc() { … }
}
DigitalWatch
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 92 -
ModeButton public void modeButton() { switch (state.value){ case state.Display : LCD.displayTime(); state.value = state.SetHours; break; case state.SetHours: LCD.displayHours(); state.value = state.SetMinutes; break; case state.SetMinutes: LCD.displayTime(); state.value = state.Display; break; } }
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 93 -
Inc public void inc() {
switch (state.value){
case state.Display : break;
case state.SetHours: LCD.incHours();
break;
case state.SetMinutes: LCD.incMinutes();
break;
}
}
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 94 -
Design Pattern: State
DigitalWatch
+ modeButton()
+ inc()
State
Display
+inc()
Hours
+inc()
Minutes
+inc()
+inc()
Comment:
This is more object oriented!
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 95 -
Two examples to show the power of state charts
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 96 -
The life cycle of an applet
init
start
stop
destroy
Loading
applet
Leaving
page Visiting
page
Discarding
page
Datavetenskap
Rogardt Heldal Classes, Objects, and Relations - 97 -
Thread states
New Thread Dead
yield
start
The run method terminates
sleep
(finish sleeping)
wait
notify
I/O finish
public final boolean isAlive()
A thread is alive if it is in the state ”Runnable” or ”Blocked” .
Blocked
Wait to be
notified
Wait for target
to finish
Wait for I/O
Sleeping
Runnable
Not
interrupted
interrupted
join
target finish blocked on I/O
Alive
interrupt
interrupt()/throws InterruptedException