ca228 software specification 2 what is an object? an object is… the physical and conceptual things...

128
CA228 Software Specificatio n 2 What is an object? An object is… the physical and conceptual things we find in the universe around us a software bundle of variables and related methods (operations) anything that supports the concept of a name an instance of a class

Upload: anna-rose

Post on 28-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

CA228 Software Specification 2

What is an object?

An object is… the physical and conceptual things we

find in the universe around us a software bundle of variables and

related methods (operations) anything that supports the concept of a

name an instance of a class

CA228 Software Specification 3

Classes

A class is a blueprint that defines the attributes and methods common to all objects of a certain kind

Classes define: attributes (state) methods (behavior)

CA228 Software Specification 4

Class attributes

Attributes hold the state of an object e.g. the state of a bank account

object might include the attributes account number account owner overdraft limit current balance

CA228 Software Specification 5

Class methods (operations)

Methods are the operations that an object can perform or suffer e.g. our bank account object might

have methods: deposit withdraw increase overdraft reduce overdraft

CA228 Software Specification 7

Objects are “Black Boxes”

The underlying implementation of an object is hidden from those that use the object

Access to the object is via its public interface This describes what attributes the

user can access and what operations can be invoked

CA228 Software Specification 8

Example

BankAccount Class

Acct #OwnerOverdraftBalance

with-draw

inc.OD

deposit

dec.OD

E-022Bob400125.00

S-3494John200225.80

H-012Mary100018,000

Instances

CA228 Software Specification 9

Abstract classes

Abstract classes are classes that embody coherent and cohesive, but incomplete concepts – no instantiated (concrete) objects e.g. the class “motor vehicle” is abstract

because it is not a complete definition for any vehicle

Provide starting points for inheritance e.g. motor vehicle can be motor car, motor

bike, motor boat, lorry, etc.

CA228 Software Specification 10

Inheritance

The process of defining new classes by reusing the features of existing classes

Only the differences between the new class and the existing class needs to be defined

Increases programmer productivity Can be found by looking for ‘IS-A’

relationships between objects

CA228 Software Specification 11

Inheritance (example)More generalized

More specialized

Superclass

Sub-class Sub-class

CarCar

EstateCar

EstateCar

SportsCar

SportsCar

CA228 Software Specification 12

Aggregation

Aggregation is the process of forming a new complex aggregate object by joining smaller less complex classes together An aid to the software development

process Can be found by looking for ‘HAS-

A’ relationships between objects

CA228 Software Specification 13

Aggregation example

Consider a Car object It is composed of a number of separate,

autonomous objects e.g. Wheel objects, Engine object, Chassis

object, Seat objects, etc. These objects may also be composed of

other objects e.g. Engine consists of Pistons, Valves, Gears,

Nuts, Bolts, etc.

CA228 Software Specification 14

Polymorphism

“taking on many forms” An ability of different classes of

objects to react to the same stimulus

CA228 Software Specification 15

Polymorphism (example)

Consider a windowing environment

Each GUI component is an object that knows how to draw itself

Can draw entire screen by telling all GUI objects to draw themselves

Application window

OK Cancel

*******Password:

Frame

Button

Editbox

Label

CA228 Software Specification 16

Encapsulation

… is the packaging together of both data and operations

An object has both state and behavior

CA228 Software Specification 17

Why use an object model?

Objects reflect the real world Objects are stable Objects reduce complexity Objects are reusable

CA228 Software Specification 19

Object-Oriented Analysis (OOA)

Make a list of candidate objects from the problem domain (requirements spec.)

Group like objects (inheritance) Look for composite objects

(aggregation) Draw object diagram List attributes and methods of each

object

CA228 Software Specification

Meyer

Before and after conditions

Harel

StatechartsGamma, et al

Frameworks and patterns,

HP Fusion

Operation descriptions and message numbering

Embley

Singleton classes andhigh-level view

Wirfs-Brock

Responsibilities

Odell

Classification

Shlaer - Mellor

Object lifecycles

Rumbaugh

OMT

Booch

Booch method

Jacobson

OOSE

Contributions to the UML

CA228 Software Specification18

UML in One Sentence

The UML is a graphical language for visualizing specifying constructing documentingartifacts of a software-intensive

system.

CA228 Software Specification19

Diagrams

A diagram is a view into a model Presented from the aspect of a particular

stakeholder Provides a partial representation of the

system Is semantically consistent with other views

In UML 1.0, there are nine standard diagrams Static views: use case, class, object,

component, deployment Dynamic views: sequence, communication

(aka communication), state machine, activity

CA228 Software Specification

UML 1.0 Models, Views, and Diagrams

Use CaseDiagramsUse Case

DiagramsUse CaseDiagrams

ScenarioDiagramsScenario

DiagramsCommunication(Collaboration)Diagrams

StateDiagramsState

DiagramsComponentDiagrams

ComponentDiagramsComponent

DiagramsDeploymentDiagrams

StateDiagramsState

DiagramsObjectDiagrams

ScenarioDiagramsScenario

DiagramsState MachineDiagrams

Use CaseDiagramsUse Case

DiagramsSequenceDiagrams

StateDiagramsState

DiagramsClassDiagrams

ActivityDiagrams

A model is a completedescription of a systemfrom a particularperspective

Models

CA228 Software Specification

UML Architecture Support

Design (Logical) View Implementation View

Process ViewDeployment View

Use Case View

4 + 1 View Model of Architecture

Class & Object DiagramsInteraction DiagramsState Machine DiagramActivity Diagram

Component DiagramInteraction Diagrams

State Machine DiagramActivity Diagram

Use Case DiagramInteraction DiagramsStatechart DiagramActivity Diagram

Class & Object DiagramsInteraction DiagramsState Machine DiagramActivity Diagram

Deployment DiagramInteraction Diagrams

State Machine DiagramActivity Diagram

Reprinted from The Unified Modeling Language Users Guide

CA228 Software Specification

Introduction to Use Case Diagrams

Use Cases: Technique for capturing functional

requirements of a system Describe typical interactions between users

of a system and the system itself. A scenario is a sequence of steps describing an

interaction between a user and a system. Scenarios model the goal of the user (an actor).

An actor is a role that a user plays with respect to the system.

A use case is a set of scenarios tied together by a common user goal.

CA228 Software Specification

Introduction to Use Case Diagrams:‘Buy a Product’ Scenario

The customer browses the catalog and adds desired items to the shoppingbasket. When the customer wishes to pay, the customer describes the ship-ping and credit card information and confirms the sale. The system checksthe authorization on the credit card and confirms the sale both immediately and with a follow-up call.

Who is the actor?

What is the actor’s goal?

What if the customer is a regular customer and youAlready know shipping and credit card information?

What happens if credit card authorization fails?

CA228 Software Specification

Contents of a Use Case Main success scenario

Sequence of numbered steps ‘Other’ scenarios:

Variations on the main success scenario

Are ‘extensions,’ can be successes or failures:

Conditions that result in different interactions from those described in the main success scenario (MSS).

CA228 Software Specification

Example Use Case Text

CA228 Software Specification

Identifying Use Cases Major distinct, complete, end-to-end processes of

using a system. Not usually one step, but a complete story.

Common “mistake”! Examples

Rent Videos Return Videos Pay Fines

CA228 Software Specification

A Sample Detailed Use CaseUse Case: Rent Items

Typical Course of Events

Actor Intentions System Responsibility

1. Customer arrives at a checkout with videos (and/or less often, video games) to rent.

2. The Customer presents their membership identification to the Clerk, who enters it into the system.

3. Presents membership information, and status of loans (usually nothing on loan, and no outstanding fines).

4. For each video or game, the Clerk records the item identification into the system.

5. Presents accumulating list of rental item titles, due dates, total rental fee, and any late charges.

6. Clerk informs Customer of total charge, and asks for payment.

7. Customer pays Clerk by cash or credit.

8. Clerk records payment into system. 9. If a credit payment, authorizes it.

10. Generates receipt and loan report.

11. Clerk gives receipt and loan report to Customer, who then leaves with the rental items.

Alternative Courses

Step 7. Customer has insufficient cash. Request a credit payment, cancel the transaction, or deduct rental items until transaction can be paid for.

Step 7: Customer has unpaid late charges and will not pay them. Customer must pay them before renting more items, so either collect full payment, or cancel the transaction.

Step 9. Failure to authorize credit payment, either because of insufficient credit or inactive authorization service. Request cash payment instead.

CA228 Software Specification

A Sample Summary Use Case Same principles as a detailed use case, but simplifies steps

and details, as a low-fidelity incomplete first draft. Useful during early requirements and scope

analysis

System Responsibilities

3. Remember rented items.

4. Calculate and present price.

6. Authorize and record payment.

Actor Intentions

1. Customer presents items to rent.

2. Clerk records items.

5. Customer pays.

CA228 Software Specification

Use Case Diagram

CA228 Software Specification

UML Second Pass: Use Case Diagrams

Used during requirements elicitation to represent external behavior

Actors represent roles, that is, a type of user of the system

Use cases represent a sequence of interaction for a type of functionality

The use case model is the set of all use cases. It is a complete description of the functionality of the system and its environment

Passenger

PurchaseTicket

CA228 Software Specification

Actors An actor models an external entity which

communicates with the system: User External system Physical environment

An actor has a unique name and an optional description.

Examples: Passenger: A person in the train GPS satellite: Provides the system

with GPS coordinates

Passenger

CA228 Software Specification

Use CaseA use case represents a class of

functionality provided by the system as an event flow.

A use case consists of: Unique name Participating actors Pre-conditions Entry conditions (triggers) Flow of events Exit conditions (success

‘guarantees’) Special requirements

PurchaseTicket

CA228 Software Specification

The <<extend>> Relationship

<<extend>> relationships represent exceptional or seldom invoked cases.

The exceptional event flows are factored out of the main event flow for clarity.

Use cases representing exceptional flows can extend more than one use case.

The direction of a <<extend>> relationship is to the extended use case

Passenger

PurchaseTicket

NoChange

<<extend>>

OutOfOrder

<<extend>>

Cancel

<<extend>>

CA228 Software Specification

Passenger

PurchaseSingleTicket

PurchaseMultiCard

NoChange

<<extend>>

Cancel

<<extend>>

<<include>>

CollectMoney

<<include>>

The <<include>> Relationship

An <<include>> relationship represents behavior that is factored out of the use case.

An <<include>> represents behavior that is factored out for reuse, not because it is an exception.

The direction of a <<include>> relationship is to the using use case (unlike <<extend>> relationships).

CA228 Software Specification

Relating Use Cases When creating the use case diagram, it can

be useful (in terms of comprehension and simplification) to: factor out shared sub-processes

use the <<includes>> relationship show precedence order (with

exceptions) use the <<extends>> relationship

CA228 Software Specification

Contents: ATMRequirements Capture

A simplified Automatic Teller Machine Which requirements are to be captured? The activities in Requirement capture

Identification of system boundaries: actors and use cases

Diagramming use cases Elaborating scenarios Diagramming scenarios

CA228 Software Specification

A Simplified Automatic Teller Machine

The ATM is associated with only one bank It gives access to all the accounts the

customer owns in the bank

Several types of transactions can be chained in a single session

Withdrawal, deposit, transfer between the customer’s own accounts, consulting an account

The customer may obtain a printed receipt for each transaction

CA228 Software Specification

A Simplified Automatic Teller Machine

The card contains an ID number an expiration date a secret code

The card must be verified by the ATM The customer cannot make more

than 3 attempts to enter the correct code, otherwise the card is swallowed

Interface Keyboard and screen, with menus The customer may cancel the

current transaction at meaningful points

CA228 Software Specification

A Simplified Automatic Teller Machine The connections with the bank are kept

to a minimum When a session is opened, a

connection makes it possible to know all the accounts the customer owns

Every night, the information about the current day transactions are transferred to the bank

From time to time an employee manually

empties the machine and/or fills it with bank notes

supplies consumables and does any maintenance that may be needed

CA228 Software Specification

Which requirements are to be captured? Functional requirements

Modeled as Use Cases Non functional requirements

Some are specific to one use case Some relate to technical issues

addressed by implementation diagrams and models

Other in some supplementary documents, out of the UML scope…

CA228 Software Specification

Identifying System BoundariesIdentifying Actors

Actors are anything which interface with the system People, other systems, hardware, software,

networks… They are roles, not necessarily full-fledged

objects Actors are not part of the system

They are just at the boundary (external to the system)

They won’t produce code!

CA228 Software Specification

Identifying System BoundariesIdentifying Actors (cont.)

ATM example Customer using

the teller machine

Bank Maintenance

technician

What about the card itself?

Customer

Bank

Technician

CA228 Software Specification

Identifying System BoundariesIdentifying Use Cases Use cases describe the services the system

must perform from the point of view of the actors Functional description From a usage point of view

CA228 Software Specification

Diagramming Use CasesTop Level Use Case Diagram

Handle Session

Transfer Daily

Maintain

Bank

Technician

Customer

associationsystem boundary

CA228 Software Specification

Diagramming Use CasesStereotyped Dependencies

HandleSession

« include »

VerifyCard

« include »

AuthentifyCustomer

« include »

Get CustomerInformation

HandleTransaction

« include »

DeliverReceipt

« extend »

CA228 Software Specification

Diagramming Use CasesStereotyped Dependencies

« include » The included use case is a mandatory part of

the including one (functionality-wise, not actor-wise)

« extend » The extending use case is an optional part of

the extended one (functionality-wise, not actor-wise)

Including« include »Included

Extended« extend »Extending

CA228 Software Specification

Diagramming Use CasesGeneralization

Handle

Transaction

Handle

Deposit

Handle

Withdrawal

Handle

Consult

Handle

Transfer

CA228 Software Specification

Diagramming Use CasesGeneralization The specialized and generalized use cases

are in a “sort of” relationship

Generalized

Specialized

CA228 Software Specification

Elaborating scenariosUse Case and Scenarios

Use cases classify the ways of using the system To each use case correspond many possible usage

scenarios Thus scenarios

are instances of use cases specify use cases

Each use case has generally a primary scenario, possibly several (a few) several secondary (more exceptional)

scenarios

CA228 Software Specification

Elaborating Scenarios for Use CasesUse Case: Handle SessionPrecondition: the ATM is freePrimary Scenario1. The Customer inserts the card

into the ATM.2. The ATM verifies the card

validity.3. The Customer authentifies with

the ATM.4. The ATM gets the Customer

information from the Bank.5. The Customer selects a

transaction.6. The Customer quits.7. The ATM ejects the card.Postcondition: the ATM is free

HandleSession

« include »

VerifyCard

« include »

AuthentifyCustomer

« include »

Get CustomerInformation

HandleTransaction

« include »

CA228 Software Specification

Elaborating Scenarios for Use CasesUse Case: Handle SessionPrecondition: the ATM is freePrimary Scenario1. The Customer inserts the card

into the ATM.2. The ATM verifies the card

validity.3. The Customer authentifies with

the ATM.4. The ATM gets the Customer

information from the Bank.5. The Customer selects a

transaction.6. The Customer quits.7. The ATM ejects the card.Postcondition: the ATM is free

Variants2a The card is invalid; the ATM swallows it; this ends the session.3a The Customer fails to authentify; the ATM swallows the card; this ends the session.4a The connection with the Bank is impossible or interrupted; the ATM ejects the card; this ends the session.5a The Customer may quit immediately.6a The Customer chooses to perform another transaction; goto step 5.* The Customer may cancel the session; the ATM ejects the card.

CA228 Software Specification

Elaborating scenariosPrimary Scenario

Use Case: Handle Session

Scenario: Primary (typical)

Precondition: the ATM is free

1. The scenario starts when the customer inserts the card

2. The card is accepted

3. The customer enters the secret code correctly

4. The ATM gets the customer information from the bank

5. The customer performs a transaction

6. When the transaction is finished, the customer may ask for another transaction (go to 5) or quit

7. The scenario is finished when the customer decides to quit; the card is ejected

Postcondition: the ATM is free

CA228 Software Specification

Elaborating scenariosExample of Secondary Scenarios

Use Case: Handle Session

Scenario: Secondary (customer interrupt)

Precondition: the ATM is free

1. The scenario starts when the customer inserts the card

2. The card is accepted

3. The customer enters the secret code correctly

4. The customer cancel the session

1. The card is ejected and the scenario is finished

Postcondition: the ATM is free

CA228 Software Specification54

Behavioral Diagrams

Used to visualize, specify, construct,document dynamic aspects of system: use case diagram sequence diagram communication diagram state machine diagram activity diagram

CA228 Software Specification55

Diagramming Scenarios: UML ways of expressing scenarios Activity diagrams

Several scenarios (even a full use case) at once

Interaction (sequence and communication) diagrams

Only one scenario per diagram Involve/introduce (high level) objects Sequence diagram

Accent on the time flow Communication diagram

Accent on the messages between objects

CA228 Software Specification56

Interaction Diagrams(Sequence and Communication)

Describe how groups of objects collaborate in some behavior Sequence diagrams

Time-oriented Communication diagrams

Message-oriented

CA228 Software Specification57

Diagramming Scenarios:Sequence Diagrams Describe one scenario Involve objects and messages

Shows a number of objects and the messages that are passed between these objects.

Accent is on the time flow of events

CA228 Software Specification58

Diagramming Scenarios:Sequence Diagrams

get_Customer_Information()

select_transaction(sel)

display_menu()

quit

Customer Bank

time card_taken

eject_cardcard_returned

insert_card

ATM

Session« new »

Transaction« new »

display_menu()

CA228 Software Specification59

Interaction and Message

An interaction is a behavior that comprises a set of messages, exchanged among a set of objects, to accomplish a specific purpose.

A message is the specification of a communication between objects that conveys information, with the expectation that some kind of activity will ensue.

CA228 Software Specification60

Sequence Diagram

A sequence diagram is an interaction diagram that emphasizes the time ordering of messages.A lifeline is a vertical dashed line that represents the lifetime of an object.A focus of control is a tall, thin rectangle that shows the period of time during which an object is performing an action.

CA228 Software Specification61

Sequence Diagram

Captures dynamic behavior (time-oriented) Purpose

Model flow of control Illustrate typical scenarios

CA228 Software Specification62

CA228 Software Specification

UML Sequence Diagrams

Used during requirements analysis To refine use case

descriptions to find additional objects

(“participating objects”) Used during system design

to refine subsystem interfaces Classes (and objects) are represented

by columns Messages are represented by arrows Activations are represented by narrow

rectangles Lifelines are represented by dashed

lines

selectZone()

pickupChange()

pickUpTicket()

insertCoins()

PassengerTicketMachine

CA228 Software Specification

UML Sequence Diagrams: Nested Messages

The source of an arrow indicates the activation which sent the message

An activation is as long as all nested activations

selectZone()

PassengerZoneButton TarifSchedule Display

lookupPrice(selection)

displayPrice(price)

price

Dataflow

…to be continued...

CA228 Software Specification65

Sequence Diagram Observations UML sequence diagram represent behavior

in terms of interactions. Complement the class diagrams which

represent structure. Useful to find participating objects. Time consuming to build but worth the

investment.

CA228 Software Specification66

Diagramming Scenarios:Communication Diagrams Describe one scenario Involve objects and messages Accent is on messages exchanged between

objects

Sequence and Communication diagrams are largely equivalent.

CA228 Software Specification67

Diagramming Scenarios:Communication Diagrams (cont.)

: Customer

: ATM

: Bank

: Session

: Transaction

1: insert_card

7: card_taken

4: select_transaction

3: get_customer_information

5: « create »

2: « create »

6: eject_card

CA228 Software Specification68

Communication Diagram

A communication diagram is an interaction diagram that emphasizes the organization of the objects that participate in the interaction.

A path is a link between objects, perhaps with a stereotype such as «local» attached.

Sequence numbers indicate the time ordering of messages, to one or more levels.

CA228 Software Specification69

Communication Diagram

Captures dynamic behavior (message-oriented)

Purpose Model flow of control Illustrate coordination of object

structure and control

CA228 Software Specification70

Communication Diagram Notation

CA228 Software Specification71

Communication Diagram Notation

CA228 Software Specification72

CA228 Software Specification73

Common Uses of Class Diagrams to model the vocabulary of the system, in terms of

which abstractions are part of the system and which fall outside its boundaries

to model simple collaborations (societies of elements that work together to provide cooperative behavior)

to model logical database schema (blueprint for conceptual design of database)

CA228 Software Specification74

UML Class Diagrams

Show static (structural) relationships between classes Associations Subtypes

CA228 Software Specification75

Class A class is a description of a set of objects that

share the same attributes, operations, relationships, and semantics.

An attribute is a named property of a class that describes a range of values that instances of the property may hold.

An operation is a service that can be requested from an object to affect behavior.

CA228 Software Specification76

Class Notation

Name

Attributes

Operations

CA228 Software Specification77

Alternative Class Notations

Name

Attributes

Operations

Responsibilities

Name

OperationsName

italics abstract

CA228 Software Specification78

Class Diagrams

CA228 Software Specification79

Attributes Syntax:

visibility name: type multiplicity = default {property string}

Example:- name: String [1] = “Untitled” {readOnly} type

can be omitted, especially if obvious Should be a simple type, not a class (use

association instead)

CA228 Software Specification80

Attributes defaultValue

can be omitted if not used. visibility

Language dependent, but there are default symbols

+ (public = everyone can see) - (private = only this class can see) # (protected = only this and subclasses can

see)

CA228 Software Specification81

Operations Syntax:

visibility name (parameter-list): return-type {property-string}

Example: + balanceOn (date, account#): Money Visibility:

+ (public), # (protected), or – (private) Parameter-list:

Comma-separated

CA228 Software Specification82

Operation Parameters Syntax:

direction name: type = default value

Direction: in out inout (i.e. both in and out)

CA228 Software Specification83

Classifying Operations A Way to Classify Operations

Query – does not change system state Modifier – changes system state

Another Way to Classify Operations Getting method – returns a value (and

nothing else) Setting method – puts a value (and nothing

else) Whether, e.g., an operation is a query or a getting

method is invisible from the outside.

CA228 Software Specification84

Relationships

Are connections between classes dependency generalization association

CA228 Software Specification85

Dependency A dependency exists between two elements if changes to

the definition of one element (the supplier) may cause changes to the other (the client).

Dependencies between classes may exist because: One class sends a message to another One class has another as part of its data One class mentions another as a parameter to an

operation If a class changes its interface, any message sent to

that class may no longer work properly. In UML, you can depict dependencies between all sorts of

elements.

CA228 Software Specification86

Dependency Example The Benefits Window class, a user interface, or

presentation class, is dependent on the Employee class: if the Employee class changes its interface, the Benefits Window may have to change.

CA228 Software Specification87

Another Dependency Example If the DataInput interface changes,

OrderReader must change.

CA228 Software Specification88

Generalization

A generalization is a “kind-of” or “is-a” relationship between a general thing (superclass or parent) and a more specific thing (subclass or child).

Shape

RectangleCircle

CA228 Software Specification89

Generalization (inheritance)

All attributes and operations of Customer also apply to instances of Personal Customer and Corporate Customer.

But the subtype classes Personal Customer and Corporate Customer should have attributes and operations that do not apply to the supertype Customer class.

Customer

Corporate CustomerPersonal Customer

CA228 Software Specification90

Class Hierarchy

CA228 Software Specification91

Association

An association is a structural relationship within which objects belonging to two or more different classes are connected to each other. (An association between objects is called a link.) Messages between objects typically ‘flow’ along association links.

CompanyPerson

CA228 Software Specification92

Associations Indicated by a line Each line has two association ends, a.k.a. roles Each end can have a role name. Each end has multiplicity (how many objects)

Number (e.g. 5) min..max (range, e.g. 1..10) * (any number) Can separate numbers and/or ranges with

commas

CA228 Software Specification93

Association Adornments name role multiplicity aggregation composition

CA228 Software Specification94

Association Name

describes nature of relationship:

can also show direction to read name:

CompanyPerson works for

CompanyPersonworks for

employs

CA228 Software Specification95

Association Roles describe “faces” that objects of a class

present to each other within association class can play same or different roles within

different associations

CompanyPersonemployee

employer

CA228 Software Specification96

Multiplicity Which number goes on which end?

The number next to a class specifies how many objects of that class can have associations.

Example: One (each) customer object can be associated

with zero or many order objects. One (each) order object is associated with exactly

one customer object.

CA228 Software Specification97

Association Multiplicity (ies) possible values for object links in two

different classes: explicit value, range, or * for “many”

Example: a Person is employed by one Company; a Company employs one or more Persons

CompanyPerson1..*

1

CA228 Software Specification98

Association Multiplicity (ies) More generally, multiplicities are defined with a

lower bound and an upper bound Lower bound may be any positive number or

zero Upper bound is any positive number or *

(unlimited) If lower bound and upper bound is the same,

you use one number 1 is equivalent to 1..1 Because it is common, * is equivalent to 0..*

Game of CanastaCanasta Players2..4

CA228 Software Specification99

Association Multiplicity (ies) The most common multiplicities are:

1 for example, an order line must belong to exactly one order

0..1 for example, an order may or may not be stamped with a date received

* for example, a particular date received may not be marked on any order, or it may be marked on any number of orders (with no upper limit).

CA228 Software Specification100

Association Multiplicity (ies) An optional relationship implies a lower

bound of 0 A mandatory relationship implies a lower

bound of 1 or more A single-valued relationship implies an

upper bound of 1 A multivalued relationship implies an

upper bound of more than 1: usually *.

CA228 Software Specification101

Association Multiplicity (ies)

CA228 Software Specification102

Association, Aggregation, Composition

Association Denoted by arrow (if unidirectional in

navigation). Signifies some sort of relationship (objects are

‘linked,’ messages flow along associations). Aggregation (‘part-of,’ not attached)

Denoted by empty diamond. Signifies something is a part of a whole.

Composition (‘part-of,’ is attached) Denoted by filled diamond. A part can only belong to one whole. Deletion of whole cascades to deletion of parts.

CA228 Software Specification103

Aggregation

Aggregation is a “whole/part” or “has-a” relationship within which the objects of one class represents a larger thing that consists of smaller things (objects in another class).

Department

Company

CA228 Software Specification104

Composition

Composition is a special form of aggregation within which the parts are inseparable from the whole.

Frame

Window

CA228 Software Specification105

Association, Aggregation, Composition

CA228 Software Specification106

Association, Aggregation, Composition

Polygon

Style

colorisFilled

*

1

Point

3..*Circle

radius

*

1

13..* 1

*

11

CA228 Software Specification107

Association Classes

An association class has properties of both an association and a class.

CompanyPerson

JobdescriptiondateHired

salary

CA228 Software Specification108

Association Classes Allow you to add attributes, operations, and other features to

associations A person may attend many weddings

We want to keep information on how awake that person was.

CA228 Software Specification109

Association Classes Can promote the association class to a full class:

But the association class (Fig 5.12) adds an extra constraint – there can only be one instance of the association class between any two participating objects.

CA228 Software Specification

State Machine and Transition• A state machine is a behavior that specifies

the sequences of states that an object goes through in its lifetime, in response to events, and also its responses to those events.

• A transition is a relationship between two states; it indicates that an object in the first state will perform certain actions, then enter the second state when a given event occurs.

CA228 Software Specification

State Machine Diagrams• Shows the behavior of an object from a

single class– shows all possible states for this object– shows how the object’s state changes as a

result of messages it receives– Useful for objects with attributes that have

a small number of states or values– Also called state diagram, statechart

diagram.

CA228 Software Specification

Object States

• State = set of values that describe an object (its condition/situation) at a specific moment in time

• State is determined based on the attribute values

overdrafted

ok

Account

balance : Float

states

CA228 Software Specification

State Changes• States may be

changed when an event occurs

• State transition: relationship indicating a state change – atomic (i.e. non-

interruptible)

overdrafted

ok

deposit(sum) withdraw(sum)

CA228 Software Specification

State Changes• Events: Messages or signals received• Events may or may

not change the state– Self-transition

overdrafted

ok

deposit

withdrawdeposit

withdraw

CA228 Software Specification

States• A state is a condition in which an object can reside

during its lifetime while it satisfies some condition, performs an activity, or waits for an event.

• A state may be indicated by values of one or more variables,

• or it may be recognized by the legal operations currently permitted.

• “A state represents the response of the object to input events.” (Rumbaugh)

• States depend on the level of abstraction in use: – My calendar says “traveling to London” (a single state)– The airline says “Atl-Mtl, Mtl-Lon.

CA228 Software Specification

Events

• An event is a significant occurrence that has a location in time and space.

• Events happen “instantaneously” (states have duration).

• “An event is a one-way transmission of information from one object to another.” (Rumbaugh).

• If there is a reply, it is a separate event.

CA228 Software Specification

Other Stuff in State Diagrams

• Guards (conditions): a logical condition that must be true, in addition to the firing of an event.

• “When you arrive to class late (event), if the lecturer is in a good mood (condition), you’ll be allowed in (new state).

CA228 Software Specification

State Notation

Idle

Cooling

Heating

Activating

Active

Nested States

CA228 Software Specification

Entry and Exit ActionsAn entry action (or operation) is the first

thing that occurs each time an object enters a particular state.

An exit action (or operation) is the last thing that occurs each time an object leaves a particular state.

Tracking

entry/setMode(onTrack)exit/setMode(offTrack)

CA228 Software Specification

ActivitiesAn activity is an interruptible sequence of

actions that an object can perform while it resides in a given state. (Actions are not interruptible.)

Tracking

do/followTarget

CA228 Software Specification

State Diagram Notation:for One State

• Activity: Can take longer and can be interrupted

• Action: Occurs quickly– “quickly” = non-interruptible– 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

State name

entry / entry-action

exit / exit-actiondo / activity-A

state variable(s)

CA228 Software Specification

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

State Diagram Notation:From One State to Another

• 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 occurs when guard evaluates to

true• Guards of transition exiting one state are

mutually exclusive• Action: Processes considered to occur quickly

and are not interruptibleNote: Each part can be omitted!

CA228 Software Specification

Initial and Final StatesThe initial (or start) state is the default

starting place for a state machine.

The (optional) final (or end) state indicates the completion of the state machine’s execution.

CA228 Software Specification

State Diagram Notation:Special States

• Start state– No event triggers allowed – may not remain in start state

• End state– Top level end state terminates a state machine– Is optional – may be omitted on any particular diagram

Initial state State-BEvent(attribute)

Start State End State

CA228 Software Specification

Example:State Transitions For an Order

Checking

do: check item

Dispatching

do: initiate delivery

Waiting

Delivered

/ get first item

Item received [some items not in stock]

Item received [all items available]

delivered

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

[All items checked && all items available]

[not all items checked] / get next item

Event

Guard

Action

Transition

State

Activity

CA228 Software Specification

Example Problem: Cancel the Order

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

• Solutions– Transitions from every state to state

“cancelled”– Superstate and single transition

CA228 Software Specification

Example:Transitions to “cancelled”

Dispatching

do: initiate delivery

Waiting

Delivered

Item received [some items not in stock ]

Item received [all items available]

delivered

Cancelled

Checkingdo: check

item

[ not all items checked ] / get next item

/ get first item

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

[ All items checked && all items available]

cancelled

cancelled

cancelled

CA228 Software Specification

Example:Superstate / Substates

Dispatching

do: initiate delivery

Waiting

Delivered

Item received [some items not in stock]

Item received [all items available]

delivered

Cancelled

Checkingdo: check

item

[not all items checked]/ get next item

/ get first item

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

[All items checked && all items available]

Active

cancelled