introduction to the uml - cs.auckland.ac.nzyen/compsci230s1c/uml-intro.pdf · the uml, an actor is...

25
Introduction to the UML Page 1 Design view Implementation view Process view Deployment view Use case view <---logical physical---> Figure 1. 4+1 view model (Booch et al, p31) Introduction to the UML Civil Engineering with Computing by Andrew Bond (Geocentrix Ltd) www.geocentrix.co.uk/oop What is the UML? “The Unified Modeling Language (UML) is a graphical language for visualizing, specifying, constructing, and documenting the artifacts of a software-intensive system” Grady Booch, James Rumbaugh, and Ivar Jacobson (1999) The Unified Modeling Language User Guide, pXV The UML: # Provides a standard means of expressing design that reflects the best practices of industry # Aims to de-mystify the process of software system modelling # Adopts the best of the Booch, Rumbaugh, & Jacobson (“the three amigos”) notations # Has been accepted as a standard by the Object Management Group (OMG) - an industry-wide body The 4+1 view model The architecture of software-intensive systems can best be described by five interlocking views, each of which is a projection into the organization and structure of the system. The use case view encompasses the use cases that describe the behaviour of the system to its end-users. The design view encompasses the classes, interfaces, and collaborations that describe the problem and its solution. This view primarily supports the functional requirements of the system. The process view encompasses the threads and processes that form the system’s concurrency and synchronization mechanisms. This view primarily addresses the performance, scalability, and throughput of the system. The implementation view encompasses the components and files that are used to assemble and release the system. The static aspects of this view are captured in component diagrams; the dynamic aspects in interaction, statechart, and activity diagrams. The deployment view encompasses the nodes that form the system’s hardware topology. This view addresses the distribution, delivery, and installation of the system. UML diagrams The UML defines various diagrams that can be used to visualize the static and dynamic parts of a computer system:

Upload: others

Post on 08-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Introduction to the UML Page 1

Design view Implementation view

Process view Deployment view

Use case view

<---logical physical--->

Figure 1. 4+1 view model (Booch et al, p31)

Introduction to the UMLCivil Engineering with Computing

by Andrew Bond (Geocentrix Ltd)www.geocentrix.co.uk/oop

What is the UML?“The Unified Modeling Language (UML) is a graphical language for visualizing, specifying,constructing, and documenting the artifacts of a software-intensive system”

Grady Booch, James Rumbaugh, and Ivar Jacobson (1999)The Unified Modeling Language User Guide, pXV

The UML:# Provides a standard means of expressing design that reflects the best practices of industry# Aims to de-mystify the process of software system modelling# Adopts the best of the Booch, Rumbaugh, & Jacobson (“the three amigos”) notations# Has been accepted as a standard by the Object Management Group (OMG) - an industry-wide

body

The 4+1 view modelThe architecture of software-intensive systemscan best be described by five interlockingviews, each of which is a projection into theorganization and structure of the system.

The use case view encompasses the use casesthat describe the behaviour of the system to itsend-users.

The design view encompasses the classes,interfaces, and collaborations that describe theproblem and its solution. This view primarilysupports the functional requirements of thesystem.

The process view encompasses the threads and processes that form the system’s concurrency andsynchronization mechanisms. This view primarily addresses the performance, scalability, andthroughput of the system.

The implementation view encompasses the components and files that are used to assemble andrelease the system. The static aspects of this view are captured in component diagrams; thedynamic aspects in interaction, statechart, and activity diagrams.

The deployment view encompasses the nodes that form the system’s hardware topology. This viewaddresses the distribution, delivery, and installation of the system.

UML diagramsThe UML defines various diagrams that can be used to visualize the static and dynamic parts of acomputer system:

Introduction to the UML Page 2

Diagram

DeploymentComponent

Object

Collaboration

Activity

Use case

Sequence

Statechart

Class

Static diagram Dynamic diagram

Figure 2. UML diagrams

Deposit money

Trading Manager

Set Limits Update Accounts

Accounting System

Analyze Risks

Price Deal

Capture DealTrader

Valuation

«uses»

«uses»

Salesperson

Limits Exceeded

«extends»

Figure 3. Example of a use case diagram (Fowler and Scott, p45)

Use case diagramsUse case diagrams help you to visualize the relationships between use cases and actors. Use casediagrams show the dynamic behaviour of a system.

Use casesA use case describes a sequence of actions that a system performs on behalf ofan actor (see below). In the UML, a use case is represented by an ellipsecontaining the name of the use case. In the example here (taken from a bankingapplication), a use case named “Deposit money” is defined.

Introduction to the UML Page 3

Deposit money

Order statement

Withdraw money

Validate accountnumber

«uses»

«uses»Money transaction

«extends» «extends»

Customer

Bank

Commercial Customer

Customer

Bank

Customer

Deposit money

Withdraw money

Order statement

A use case describes what a system does, but does not specify how it does it.

ActorsAn actor is a role that a user plays when interacting with the computer system. In thiscontext, a user may be a human, a hardware device, or even another computer system. Inthe UML, an actor is represented by a stick figure with the name of the actor beneath it. Inthe example here, an actor named Customer is defined.

An actor describes who uses the system.

System boundariesA system boundary is exactly what its name implies: the boundary of somesystem. In the UML, a system boundary is represented by a rectangularbox with the name of the system inside it. In the example here, the systemboundary of a bank is shown.

AssociationsIn a use case diagram, an association typically represents arelationship between an actor and one or more use cases.Associations are represented in the UML by straight linesconnecting the actor to the use cases he or she carries out. Inthe example here, the customer deposits money, withdrawsmoney, and orders a statement – all of which are within theboundaries of the bank’s system.

Actors may be connected to use cases only by association.An association between an actor and a use case indicatesthat they communicate with each other, possibly by sendingand receiving messages.

Generalization of actorsIn a use case diagram, you can define general types of actors andspecialize them using generalization relationships.

Generalization is represented in the UML by a white arrowheadpointing from the specialized thing to the generalized thing. In theexample here, Commercial Customer is a special type of Customer(and Customer a general type of Commercial Customer).

Generalization of use casesIn a use case diagram, you can also definegeneral types of use cases and specializethem using generalization relationships.

As for actors, generalization of use cases isrepresented in the UML by a whitearrowhead pointing from the specialized tothe generalized use case. However, theserelationships are typically stereotyped by oneof two keywords, extends or uses, dependingon their intent:# Extends indicates that the specialized use

case is similar to the general use case but does something more (typically, the extended usecase deals with a variation of the general use case)

Introduction to the UML Page 4

+Add(in who : Student)+Remove(in who : Student)+GetAllStudents()+Add(in which : Department)+Remover(in which : Department)+GetAllDepartments()

-name : std::string-address : std::string-phone_number : std::string

University

+Add(in who : Instructor)+Remove(in who : Instructor)+GetAllInstructors()

-name : std::string

Department

11..*

-name : std::string-id : int

Course

1..*

1..*

-name : std::string

Instructor

<assigned to

1..*

1..*

0..1 -chairperson 0..1

-name : std::string-id : int

Student

<member

1..*

*

attends>*

*

<teaches

*

1..*

Figure 10. Example class diagram (based on Figure 8-3 of Booch et al., 1999)

Person

# Uses indicates that the specialized use case is a common part of several use cases and has beenfactored out to avoid repetition

In the example here, Deposit money and Withdraw money both extend Money transaction. Orderstatement and Money transaction both use Validate account number. Since generalizationrelationships are transitive, this implies that Deposit money and Withdraw money also use Validateaccount number.

Example from the literatureThe use case diagram at the start of this section shows a financial trading system. There are fouractors involved (Trading Manager, Trader, Salesperson, and Accounting System) and seven usecases.

The relationships between the actors and use cases are as follows:# The Trading Manager sets limits# The Trader analyses risks, prices deals, and captures deals# The Salesperson also captures deals# The Accounting System updates accounts# Two uses cases (Analyze Risks and Price Deals) use the Valuation use case# The use case Limits Exceeded extends Capture Deal

Class diagramsClass diagrams help you to visualize the relationships between classes, interfaces, andcollaborations. Class diagrams show the static (structural) design of a system.

ClassesIn the UML, a class is represented by a rectangle containing thename of the class. In the example here, a class named Person isdefined.

// C++ exampleclass Person {};

Introduction to the UML Page 5

Family Person

Person Dogowns>

Person Dog

owner

pet

Person Dog

1

0..*

AssociationsAn association is a relationship in which an object of one type is connected to an object of anothertype.

Associations arerepresented in the UMLby lines connecting therespective classes. Toimprove understanding,associations may be named by placing a word or words above or below the connecting line. Thedirection in which the name is read is indicated by an (optional) arrow. In the example here, theperson owns the dog.

The roles played by eachclass in an associationmay be named by placinga word or words at theends of the association. Inthe example here, theperson is the owner of the dog and the dog is the person’s pet.

In many situations, one or more objects of a particular class may be associated with one or moreobjects of another class. This is called the multiplicity of the association and is represented bynumbers placed at the ends of the association:# 1 means exactly one object of this class is involved in the association# 0..1 means either zero or one objects are involved# 0..* means zero or more objects are involved# 1..* means one or more objects are involved# n (where n is an integer) means exactly that number of objects are involved

In the example here, theperson owns zero ormore dogs, but each dogis owned by exactly oneperson.

Associations thatrepresent “whole/part” or“has-a” relationshipsbetween classes areknown as aggregation.Aggregation isrepresented in the UML by adding a diamond next to the aggregate class. In the example here,Family represents the “whole” and Person the “part”.

// C++ example// decision to use a set is an implementation detail#include <set>

class Person {};class Family{

std::set<Person*> members; // not owned by Family};

Introduction to the UML Page 6

Family Person

0..*

2..*

Person Arm<is attached to

1

2

Dog

Alsatian

Specifying multiplicities inthis example addsinformation that will beuseful during theimplementation of classFamily. Assuming that afamily must consist of at least two people and that any one person can be a member of zero, one,or more families (e.g. through marriage), the UML class diagram representing this association isshown above.

There is a special form ofaggregation in which thelifetime of the partcorresponds to that of thewhole. This “owns-a”relationship is known ascomposition and is represented in the UML by a black diamond next to the aggregate class. In theexample here, the person has exactly two arms (assuming that he/she has not lost one due to anaccident!) and each arm is an integral part of exactly one person (assuming we are not modellingtransplants!). When the person dies (i.e. an object of class Person is destructed), the arms die too(i.e. both objects of class Arm are destructed too).

// C++ exampleclass Arm {};class Person{

// created/destroyed at the same time as Person...Arm left_arm;Arm right_arm;

};

GeneralizationGeneralization is a relationship between classes in which one class (the “derived” or “child” class) isa more specialized version of the other (the “base” or “parent” class). Generalization represents “is-a” relationships between classes.

Generalization is represented in the UML by a white arrowhead pointingto the more general class. In the example here, the class Alsatian is derivedfrom the class Dog, indicating that an Alsatian is a more specializedversion of dog (and a dog is a more generalized version of an Alsatian). Inthis class hierarchy, Dog is Alsatian’s parent and Alsatian is Dog’s child.

// C++ exampleclass Dog {};class Alsatian : public Dog {};

/* When a class is derived publically from another class, the childclass has access to all its parent’s public and protected membervariables/functions. If you omit the keyword “public”, then the classis derived privately from its parent - and only the parent’s publicmember variables/functions are accessible. In most cases you wantpublic derivation. */

A class that has no parents is called a “root” class and one that has no children is called a “leaf”.

Introduction to the UML Page 7

Animal

Dog

Alsatian Labrador

Cricketer

Bowler

AllRounder

Batsman

operation()

attribute

Class

Polymorphic classes allow their operations to bechosen at run-time according to the type of objectfor which the operation is called. Abstract classesare incomplete (they have at least one operationwhich is undefined, although its signature is given)and cannot be created – the compiler will ensurethis. By contrast, concrete classes are complete (alltheir operations are defined) and therefore can becreated. Abstract classes are indicated in the UMLby writing their names in italics: concrete classesare indicated by normal text.

In the example here, Animal is an abstract rootclass, whereas Alsatian and Labrador are concreteleaf classes.

// C++ exampleclass Animal{protected:

Animal(); // default c’tor accessible to derived classes only};class Dog : public Animal {};class Alsatian : public Dog {};class Labrador : public Dog {};

Specialization is a transitive relationship: an Alsatian “is-a” Dog and a Dog “is-a(n)” Animal impliesthat an Alsatian “is-a(n)” Animal.

Classes that derive from more than oneparent are said to be “multiply-inherited”. Inthe example here, class AllRounder isderived from both Bowler and Batsman,who in turn are derived from Cricketer. AnAllRounder is therefore also a Cricketer(twice over, in fact – a problem that makesmultiple inheritance tricky to implementcorrectly and a reason why Java does notallow it).

// C++ exampleclass Cricketer {};class Bowler :

public Cricketer {};class Batsman :

public Cricketer {};class AllRounder :

public Bowler, publicBatsman {};

Attributes, operations, and responsibilitiesClass icons can be divided into compartments to show the class’sattributes, operations, and responsibilities:# Attributes (C++ member variables) are shown in a compartment just

below the class name# Operations (C++ member functions) are shown in a compartment just

below the class attributes

Introduction to the UML Page 8

+PublicOperation()#ProtectedOperation()-PrivateOperation()

+public_attribute#protected_attribute-private_attribute

ClassShowingVisibilities

PerInstanceOperation()PerClassOperation()

per_instance_attributeper_class_attribute

ClassShowingClassScope

+Person()+CelebrateBirthday() : void+DiscoverSecretOfYouth() : void+GrowOldFast(in years : int = 10) : void+HowOld() : int

-age : int

Person

# Responsibilities are (optionally) shown in a separate compartment at the bottom of the classicon

When drawing a class diagram, you may choose to show or hide any of the compartments (otherthan the one that names the class, which must always be present).

The visibility of each attribute/operation is indicated by a symbolplaced in front of its name:# + for public visibility: this attribute/operation can be accessed

by functions in any part of the program# # for protected visibility: this attribute/operation can be

accessed by functions in the class itself or any class derived fromit

# - for private visibility: this attribute/operation can be accessedby functions in this class alone

// C++ exampleclass ClassShowingVisibilities{private:

int private_attribute;void PrivateOperation();

protected:int protected_attribute;void ProtectedOperation();

public:int public_attribute;void PublicOperation();

};

Class attributes/operations (e.g. C++ static membervariables/functions) are underlined.

// C++ exampleclass ClassShowingClassScope{

int per_instance_attribute;static int per_class_attribute;void PerInstanceOperation();static void PerClassOperation();

};

The syntax for describing attributes is as follows:

name : type = initial_value

and that for describing operations:

name(argument_name : type = default_value, ...) : return_type

In the example here, Person has one private attribute: hisor her age (of type int) and five operations, all of whichare public. Person’s constructor takes no arguments andreturns nothing; CelebrateBirthday andDiscoverSecretOfYouth take no arguments and returnvoid; GrowOldFast takes one argument (an int, whichtakes a default value of 10 if not specified) and returns

Introduction to the UML Page 9

+Speak(in os : std::ostream&) : void

Animal

+Speak(in os : std::ostream&) : void

Dog

+Speak(in os : std::ostream&) : void

Cat

+Speak(in os : std::ostream&) : void

Mouse

Mouse

std::ostream

Dog Cat

Animal

void; and HowOld takes no arguments and returns an int.

// C++ exampleclass Person{private:

int age; // in yearspublic:

Person(); // set age to 0 yearsvoid CelebrateBirthday(); // increase age by 1 yearvoid DiscoverSecretOfYouth(); // decrease age by 10 yearsvoid GrowOldFast(int years = 10); // increase age by value of

yearsint HowOld() const; // return age

};

Polymorphic operations are chosen at run-time according to the type of object for which theoperation is called. Abstract operations are incomplete, i.e. the operation’s signature is declared butno body is defined; whereas concrete operations have both a signature and a body. Abstractoperations are indicated in the UML by writing their names in italics: concrete operations areindicated by normal text.

In the example here, Speak is an abstract operation in class Animal but a concrete operation inclasses Dog, Cat, and Mouse. Thus if the operation Speak is called for an object of type Cat, it isCat’s version of Speak that gets called.

DependenciesA dependency is arelationship in whichan object of onetype uses an objectof another type, andtherefore dependson it. Dependenciesare represented inthe UML by adashed line with anopen arrow pointingfrom the dependentclass to the class it

Introduction to the UML Page 10

: Car

: Wheel : Wheel : Wheel : Wheel

: Engine

depends upon. In the example here, Animal, Dog, Cat, and Mouse all depend on std::ostream,because the latter class is an argument in their operation Speak (which is not shown on thisdiagram). If the specification of std::ostream should change, then all of these classes would need tobe re-compiled.

Example from the literatureThe class diagram at the start of this section shows the associations between a number of classesthat might be used to model a University teaching programme. The diagram describes five classes,University, Department, Course, Student, and Instructor, each of which has a name (modelled by astring from the standard library), some of which have an ID number, and one of which has anaddress and phone number.

The relationships between these classes are as follows:1. The University has one or more Departments2. Each Department belongs to only one University3. The University has a any number of Students4. Each Student is a member of one or more Universities5. Each Student attends any number of Courses and each Course has any number of Students on

it6. Each Instructor teaches on any number of Courses and each Course has one or more

Instructors7. Each Course is associated with one or more Departments and each Department is associated

with one or more Courses8. Each Instructor is assigned to one or more Departments; and is the chairperson of zero or one

Departments9. Each Department has one or more Instructors and either zero or one Instructors as a

chairperson

The classes University and Department has operations for adding, removing, and getting the objectsthey aggregate. Department’s Add() and Remove() operations take a single parameter named whoof type Instructor; the UML diagram does not indicate the return type of Department’s operationGetAllInstructors(), indicating that this is an implementation detail.

Object diagramsObject diagrams show a set ofobjects at a specific moment intime.

ObjectsObjects are shown by simplerectangles, with the name andtype of object underlined:

Vauxhall : Car

Where the name of the objectis irrelevant, it can be omitted:

: Car

When the name of the object is relevant, but not its type, the type may be omitted:

Vauxhall :

Introduction to the UML Page 11

Car

Wheel

Engine

1

4

1

1

: Customer : Clerk : Manager

: VideoStore

Report loss of tape()

Get record of rental()

Look up rental()

Return rental()

Refer to Manager()

Talk to Manager()

Negotiate fee()

Look up tape history()

Find tape records()

Return record()

Pay()

Figure 29. Example sequence diagram (Liberty, 1998, p50)

: Diner : Waiter : Chef

m : Meal

Order()

Communicate order()

<<create>>()

Cook()

Ready()

Ready()

Collect()

Ready()

Serve()

Eat()

Request bill()

Bill()

Pay()

LinksLinks are shown by solid lines joining the objects which are linked.

Similarity to class diagramsObject diagrams are closely related to classdiagrams, as the diagram here illustrates. In objectdiagrams, names are underlined and multipleobjects are represented by separate boxes ratherthan numbers at one end of a link.

Sequence diagramsSequence diagrams are interaction diagrams thatemphasize the time ordering of messages.Sequence diagrams show objects arranged alongthe top X-axis and messages, ordered in increasingtime, along the Y-axis.

ObjectsObjects are shown by simplerectangles, with the name and type ofobject underlined:

Blockbuster : VideoStore

Where the name of the object isirrelevant, it can be omitted:

: VideoStore

If an object represents an actor in thesystem, then a stick figure can beused in place of the rectangle.

LifelinesAn object’s lifeline represents the timeit remains in existence. During thatexistence, there are times when theobject will be active (denoted by awide band) and times when it isinactive (denoted by a dashed line).

If an object is created during the timespan covered by the sequencediagram, then its symbol is placed atthe point it first comes into existence(see the example showing m : Mealcoming into existence once it hasbeen created by the : Chef).

The end of an object’s lifeline isdenoted by a cross.

MessagesMessages are shown by solid lines

Introduction to the UML Page 12

: Customer

: Clerk

: Manager

: VideoStore

1. Report loss of tape()

5. Refer to Manager()

2. G

et re

cord

of r

enta

l()

4. R

etur

n re

cord

()

3. Look up rental()8. Find tape records()

6. Talk to manager()

10. Negotiate fee()

11. Pay()

7. Look up tape history()

9. Return record()

Figure 31. Example collaboration diagram (Liberty, 1998,p61)

with solid arrows pointing to the recipient of the message. The duration of a message is representedby the vertical distance between the beginning and end of the line. Thus, an instantaneous messageis denoted by a horizontal line (e.g. Order() in the example alongside) and a message taking sometime by a sloping line (e.g. Cook()).

The response to a message is denoted by a dashed line.

Each message has a name which represents the function call that implements the message.Parameters can be shown within the brackets after the message name, if desired.

A message that involves creation of another object is labelled <<create>>.

Collaboration diagramsCollaboration diagrams are interactiondiagrams that emphasize theorganization of the objects thatparticipate in an interaction.Collaboration diagrams are similar toobject diagrams in the way they showobjects and the links between them.In addition, collaboration diagramsshow the direction of messagesbetween the objects.

ObjectsObjects are shown by simplerectangles, with the name and type ofobject underlined. If an objectrepresents an actor in the system,then a stick figure can be used inplace of the rectangle.

MessagesMessages are shown by solid lineswith solid arrows pointing to therecipient of the message. The ordering of messages is denoted by a sequence of numbers and/orletters: e.g. 1, 2, 3a, 3b, 3c, 4, 5. The name of the message follows its order number.

Introduction to the UML Page 13

: Diner : Chef

m : Meal

: Waiter

1. Order()

9. Serve()

11. Request bill()

12. Bill()

13. Pay()

2. Communicate order()

7. Ready()

3. Prep

are()

4. Rea

dy()

5. Coo

k()

6. Rea

dy()

8. Collect()

10. Eat()

Activity diagramsActivity diagrams show the flow from activity to activity. An activity is an on-going non-atomicexecution within a state machine. Activities ultimately result in some action, which results in achange of state of the system or the return of a value.

Introduction to the UML Page 14

Find beverage

[found coffee]

Put coffee in filter

Put filter in machine

Add water to reservoir Get cups

Turn on machine

Brew coffee

[no coffee]

Get can of cola

[found cola]

[no cola]

Pour coffee Drink beverage

Develop plan count := count + 1

Select site

Commission architect

Action and activity statesAn action state is represented in the UML by a rectangle

with rounded corners, containing thename of the action. An action can bedescribed by the use of simple text,such as Develop plan, or by an expression, such as count := count + 1. Theexample here shows both forms of action state.

An activity state is also represented by a rectangle with rounded corners,containing the name of the activity.

Initial and final states are represented by black circles without or with(respectively) a surrounding ring. In the example here, the initial state leads intothe action state Select site and Commission architect is the last action statebefore the final state.

TransitionsA transition is represented by a solid line with an open arrow at one end.

Branches and guardsBranches are represented in one of two ways: either explicitly, by a small white

Introduction to the UML Page 15

diamond, or implicitly, by multiple transitions leaving an activity or action state.

In the example above, the activity Find beverage branches according to whether coffee is found ornot. If it is not, a further branch occurs, depending on whether cola is found or not.

Forking and joiningA fork is denoted by a thick line from which several transitions leave but only one enters. A join isdenoted by a thick line from which one transition leaves but several enter.

SwimlanesSometimes it is helpful to place activities in what a re termed swimlanes which represent differentparts of the system. Swimlanes are separated from each other by vertical lines.

Statechart, component, and deployments diagrams...are outside the scope of this workshop. Please refer to the books below for further information.

References

UML1. Martin Fowler with Kendal Scott (1999), UML Distilled (2nd edition), Addison-Wesley, 224pp,

(ISBN 0-201-65783X), £192. Grady Booch, James Rumbaugh, & Ivar Jacobson (1999), The Unified Modeling Language User

Guide, Addison-Wesley, 482pp (ISBN 0-201-57168-4), £383. Jesse Liberty (1998), Beginning Object-Oriented Analysis and Design with C++, Wrox Press,

(ISBN 1-861001-33-9), £334. Pierre-Alain Muller (1997), Instant UML, Wrox Press, 343pp (ISBN 1-861000-87-1), £215. Rob Pooley & Perdita Stevens (1999), Using UML, Addison-Wesley, 255pp (ISBN

0-201-36067-5), £25Prices quoted by Amazon.co.uk (January 2001)

Introduction to the UML Page 16

Class exercises

Exercise 1# Identify the actors and use cases for a computerised version of the classic card game Pontoon.

Exercise 2# Identify a set of classes to implement Pontoon, including the relationships between them. Draw

a class diagram corresponding to these classes and relationships.# Develop C++ code to implement the class diagram.

Exercise 3# Draw an object diagram representing a particular moment during a game of Pontoon, when a

player has the following card: Ace of Spades, 3 of Diamonds, and 7 of Hearts

Exercise 4# Draw either a sequence diagram or a collaboration diagram to represent playing of a single

hand of Pontoon

Introduction to the UML Page 17

Rules of Pontoon

From The Penguin Book of Card Games, by David Parlett (1978), Penguin Books, 474pp (ISBN 0 14046 344 5)

A banking game for 3-10 players, 4-6 best. Use a standard 52-card pack. Suits are irrelevant: all thatcounts is the numerical face-value of the cards:# From Two to Ten count 2 to 10 respectively# Court cards count 10 each# An ace counts either 1 or 11 at its holder's discretion

Banker...# Shuffles the cards before his first deal, but not thereafter# Deals one card each, face down, dealer's last

All except the banker may look at their card. Everyone gets a second card and more may be boughtthereafter. The object is to finish with a better hand than the banker's

A hand whose cards total over 21 is bust and loses. A hand totalling 16-21 beats the banker only ifthe latter has a lower count or is bust. There are three special hands:# Pontoon is 21 on two cards# Royal Pontoon is three Sevens (punter only)# A five card trick is a hand of five cards that is not bust

Pontoon beats the banker unless he also has a pontoon and wins double. Royal Pontoon beats thebanker and wins treble. Three Sevens for the banker counts as 21 and is beaten by pontoon. A fivecard trick beats anything the banker has, except another five card trick, and wins double.

Each punter looks at his first card and stakes upon it an amount that lies within previously agreedlimits, and then gets a second card (as does the banker). If the banker has pontoon he reveals it andwins, collecting double everyone's stakes. If a punter has pontoon, he turns the ace over andreceives no more cards.

A punter with two cards of identical rank may split them and play two hands, staking the sameamount on the second hand as on the first. The banker may not split. The punter then either:# Sticks, provided his score is 16 or over# Buys a card (dealt face down)# Twists a card (dealt face up)The punter may not buy after twisting.

When buying a card, the punter pays not less than what he paid for his previous card nor more thanhis total stake so far. The fifth card of a five card trick is always dealt face up, even if bought. Thebanker plays after all the punter have played and pays only those punters who have beaten hisscore.

Introduction to the UML Page 18

Program 1//----------------------------------------------------------------------------// Civil Engineering with Computing: OOP with C++, UML, and the STL// Introduction to the UML// Copyright: ©2001 Geocentrix Ltd. All Rights Reserved.// Component:Program1.exe// File: Program1.cpp// Overview: implementation of Program1//---------------------------------------------------------------------------#include <iostream>

using std::cout;using std::endl;

//---------------------------------------------------------------------------// class Person

class Person{public: Person() { cout << "Person born" << endl; } ~Person() { cout << "Person dies" << endl; }};

//---------------------------------------------------------------------------// main test program

int main(){ cout << "About to create a person" << endl; Person me; cout << "About to return from main()" << endl; return 0;}//---------------------------------------------------------------------------// Revision history// 1.00 29/01/01 AJB modified for Feb 2001 class// 1.10 28/09/01 AJB modified for Sept 2001 class//----------------------------------------------------------------------------

Program 2//----------------------------------------------------------------------------// Civil Engineering with Computing: OOP with C++, UML, and the STL// Introduction to the UML// Copyright: ©2001 Geocentrix Ltd. All Rights Reserved.// Component:Program2.exe// File: Program2.cpp// Overview: implementation of Program2//---------------------------------------------------------------------------#include <iostream>

Introduction to the UML Page 19

#include <string>

using std::cout;using std::endl;using std::string;

//---------------------------------------------------------------------------// class Person

class Person{public: Person(const string& a_name); ~Person(); string Name() const { return name; }private: string name;};

Person::Person(const string& a_name) : name(a_name){ cout << Name() << " born" << endl;}

Person::~Person(){ cout << Name() << " dies" << endl;}

//---------------------------------------------------------------------------// main test program

int main(){ cout << "About to create a person" << endl; Person me("Andrew"); cout << "My name is " << me.Name() << endl; cout << "About to return from main()" << endl; return 0;}//---------------------------------------------------------------------------// Revision history// 1.00 29/01/01 AJB modified for Feb 2001 class// 1.10 28/09/01 AJB modified for Sept 2001 class//----------------------------------------------------------------------------

Program 3//----------------------------------------------------------------------------// Civil Engineering with Computing: OOP with C++, UML, and the STL// Introduction to the UML// Copyright: ©2001 Geocentrix Ltd. All Rights Reserved.

Introduction to the UML Page 20

// Component:Program3.exe// File: Program3.cpp// Overview: implementation of Program3//---------------------------------------------------------------------------#include <iostream>#include <string>

using std::cout;using std::endl;using std::string;using std::ostream;

//---------------------------------------------------------------------------// class Person

class Person{public: Person(const string& firstname, const string& surname, bool male); ~Person(); string Name() const { return firstname + " " + surname; } unsigned int Age() const { return age; } void CelebrateBirthday() { ++age; } bool IsMale() const { return male; } bool IsFemale() const { return !IsMale(); } void Speak(ostream& os) const;private: string firstname; string surname; bool male; unsigned int age;};

Person::Person(const string& firstname, const string& surname, bool male) : firstname(firstname) , surname(surname) , male(male) , age(0){ cout << Name() << " born" << endl;}

Person::~Person(){

Introduction to the UML Page 21

cout << Name() << " dies" << endl;}

void Person::Speak(ostream& os) const{ os << "My name is " << Name() << endl; os << "I am a "; if(IsMale()) os << "male"; else os << "female"; os << " aged " << Age() << endl;}

//---------------------------------------------------------------------------// main test program

int main(){ cout << "Create a person" << endl; Person me("Andrew", "Bond", true); me.Speak(cout);

cout << "Live 40 uneventful years" << endl; for(unsigned int i = 0; i < 40; ++i) me.CelebrateBirthday(); me.Speak(cout);

cout << "About to return from main()" << endl; return 0;}//---------------------------------------------------------------------------// Revision history// 1.00 29/01/01 AJB modified for Feb 2001 class// 1.10 28/09/01 AJB modified for Sept 2001 class//----------------------------------------------------------------------------

Program 4//----------------------------------------------------------------------------// Civil Engineering with Computing: OOP with C++, UML, and the STL// Introduction to the UML// Copyright: ©2001 Geocentrix Ltd. All Rights Reserved.// Component:Program4.exe// File: Program4.cpp// Overview: implementation of Program4//---------------------------------------------------------------------------#include <iostream>#include <string>

using std::cout;using std::endl;using std::string;using std::ostream;

Introduction to the UML Page 22

//---------------------------------------------------------------------------// class Person

class Person{public: Person(const string& firstname, const string& surname, bool male); ~Person(); string Name() const { return firstname + " " + surname; } unsigned int Age() const { return age; } void CelebrateBirthday() { ++age; } bool IsMale() const { return male; } bool IsFemale() const { return !IsMale(); } void Speak(ostream& os) const; bool CanMarry() const; void Marry(Person& fiancee); bool IsMarried() const { return spouse; }private: string firstname; string surname; bool male; unsigned int age; const Person* spouse;};

Person::Person(const string& firstname, const string& surname, bool male) : firstname(firstname) , surname(surname) , male(male) , age(0) , spouse(0){ cout << Name() << " born" << endl;}

Person::~Person(){ cout << Name() << " dies" << endl;}

bool Person::CanMarry() const{

Introduction to the UML Page 23

if(IsMarried()) { cout << Name() << " is already married!" << endl; return false; }

if(Age() < 18) { cout << Name() << " is too young to marry!" << endl; return false; }

return true;}

void Person::Marry(Person& fiancee){ if(CanMarry() && fiancee.CanMarry()) { if((IsMale() && fiancee.IsFemale()) || (IsFemale() && fiancee.IsMale())) { spouse = &fiancee; fiancee.spouse = this; cout << "Ding dong bells!" << endl; } else cout << "Unenlightened times. No inter-sex marriages allowed!" << endl; }}

void Person::Speak(ostream& os) const{ os << "My name is " << Name() << endl; os << "I am a "; if(IsMale()) os << "male"; else os << "female"; os << " aged " << Age() << endl; os << "I am "; if(IsMarried()) os << "married to " << spouse->Name() << endl; else os << "not married" << endl;}

//---------------------------------------------------------------------------// main test program

int main(){ cout << "Create a person" << endl; Person Andrew("Andrew", "Bond", true); Andrew.Speak(cout);

cout << "Create a potential wife" << endl; Person Jenny("Jenny", "Bond", false);

Introduction to the UML Page 24

Jenny.Speak(cout);

cout << "Live 25 great years" << endl; for(unsigned int i = 0; i < 25; ++i) { Andrew.CelebrateBirthday(); Jenny.CelebrateBirthday(); } Andrew.Speak(cout);

cout << "Get married" << endl; Andrew.Marry(Jenny); Andrew.Speak(cout);

cout << "Live 15 miserable years" << endl; for(unsigned int i = 0; i < 25; ++i) { Andrew.CelebrateBirthday(); Jenny.CelebrateBirthday(); } Andrew.Speak(cout);

cout << "About to return from main()" << endl; return 0;}//---------------------------------------------------------------------------// Revision history// 1.00 29/01/01 AJB modified for Feb 2001 class// 1.10 28/09/01 AJB modified for Sept 2001 class//----------------------------------------------------------------------------

Introduction to the UML Page 25

Player

Dealer

Twist

Stick

Place bet

Deal card Deal hand«uses»

«extends»

Collect lostbets Pay won bets

Betting

«extends» «extends»«extends»

Play

«extends»

«extends»

Deal

«extends»

«uses»

«extends»

Shuffle deck«extends»

Answers to the class exercises

Exercise 1: use case diagramIdentify the actors and use cases for a computerised version of the classic card game Pontoon.