Anda di halaman 1dari 136

Unified Modeling Language

SWE 513 UML tutorial Part I


Grkan Gr

Agenda
General Software Modeling General UML UML Diagrams

Functional Requirements Structure Behavior

Design patterns (optional)

SWE513 Spring 2010 - UML tutorial Part I

Resources
These slides are a mashup from different sources, i.e. all the credits go to them.. Sommervilles book: Software Engineering lecture slides Genix UML tutorial: http://www.genixcorp.com/ba/uml.ppt Tom Hortons Object-Oriented Analysis and Design lecture material: http://www.cs.virginia.edu/~horton/cs494/slides/ Amblers book: The Object Primer D. Schmidts (Boeing example and design patterns part) tutorial : http://www.cs.wustl.edu/~schmidt/tutorialspatterns.html UML for Systems Engineering,:watching the wheels, 2nd Ed. , Jon Holt, IET Professional Applications of Computing Series, 2007.
SWE513 Spring 2010 - UML tutorial Part I

Key Points of Software Modeling


A model is an abstract system view. Complementary types of model provide different system information. Context models show the position of a system in its environment with other systems and processes. Data flow models may be used to model the data processing in a system. State machine models model the systems behaviour in response to internal or external events.

SWE513 Spring 2010 - UML tutorial Part I 4

Key Points (cont.)


Semantic data models describe the logical structure of data which is imported to or exported by the systems. Object models describe logical system entities, their classification and aggregation. Sequence models show the interactions between actors and the system objects that they use. Structured methods provide a framework for developing system models.

SWE513 Spring 2010 - UML tutorial Part I 5

Object Oriented Methods

What are object-oriented (OO) methods?

OO methods provide a set of techniques for analyzing, decomposing, and modularizing software system architectures In general, OO methods are characterized by structuring the system architecture on the basis of its objects (and classes of objects) rather than the actions it performs

What are the benefits of OO?

OO enhances key software quality factors of a system and its constituent components
In general, systems evolve and functionality changes, but objects and classes tend to remain stable over time
SWE513 Spring 2010 - UML tutorial Part I 6

What is the rationale for using OO?

UML

Is a language. It is not simply a notation for drawing diagrams, but a complete language for capturing knowledge (semantics) about a subject and expressing knowledge (syntax) regarding the subject for the purpose of communication.

It is the result of unifying the information systems and technology industrys best engineering practices (principals, techniques, methods and tools).
SWE513 Spring 2010 - UML tutorial Part I 7

UML (contd)

Unified because it
Combines main preceding OO methods (Booch by Grady Booch, OMT by Jim Rumbaugh and OOSE by Ivar Jacobson)

Modeling because it is
Primarily used for visually modeling systems. Many system views are supported by appropriate models

Language because
It offers a syntax through which to express modelled knowledge

SWE513 Spring 2010 - UML tutorial Part I

UML Elements

Functional requirements view


Emphasizes the functional requirements of the system from the user's point of view.

Static structural view


Emphasizes the static structure of the system using objects, attributes, operations, and relationships.

Dynamic behavior view


Emphasizes the dynamic behavior of the system by showing collaborations among objects and changes to the internal states of objects.

SWE513 Spring 2010 - UML tutorial Part I

UML (again)

What it is
A language for capturing and expressing knowledge A technology for visual development modeling A set of well-founded guidelines A milestone generator A popular (therefore supported) technology

What it is not
A visual programming language or environment A database specification tool A development process (i.e. an SDLC) A silver bullet A quality guarantee
SWE513 Spring 2010 - UML tutorial Part I 10

UML (again)

The UML is a standard representation devised by the developers of widely used object-oriented analysis and design methods. It has become an effective standard for object-oriented modelling. Notation
Object classes are rectangles with the name at the top, attributes in the middle section and operations in the bottom section; Relationships between object classes (known as associations) are shown as lines linking objects; Inheritance is referred to as generalisation and is shown upwards rather than downwards in a hierarchy.

SWE513 Spring 2010 - UML tutorial Part I

11

UML Diagrams

Functional Requirements
Use-Case (relationship between actors and system functions) Class (static class structure) Object (same as class - only using class instances i.e. objects) Package (logical grouping of classes) Component (code structure) Deployment/Implementation (mapping of software to hardware) State (states of objects in a particular class) Sequence (Object message passing structure) Collaboration/Communication (same as sequence but also shows context - i.e. objects and their relationships) Activity (sequential flow of activities i.e. action states)
SWE513 Spring 2010 - UML tutorial Part I 12

Structure

Behavior

Main 4 UML Diagrams


Use-Case Class Sequence State/Statechart

SWE513 Spring 2010 - UML tutorial Part I

13

The Use-Case Diagram Use-

SWE513 Spring 2010 - UML tutorial Part I

14

Use Case Diagram

Components
Actor Goals Relationships

Use-case Relationship
Uses Consumes Generalization - Specialization Extends - Inherits

SWE513 Spring 2010 - UML tutorial Part I

15

Requirements

Defining what the system should do


What the clients needs (as opposed to wants) Not how the solution should be designed or implemented

We recognize three iterative activities :


Elicitation: capturing information from sources Documentation: putting it on paper Validation: confirming it meets users needs

Analysis (or definition) versus Specification


Customer-oriented requirements Developer-oriented requirements

SWE513 Spring 2010 - UML tutorial Part I

16

Specification Documents

Steven McConnell (IEEE Software, Oct. 2000) says any of the following are called requirements document:
Half-page summary of software product vision Two-page key features list 50-page list of details about end-user requirements (he calls this a function-requirements document) 250-page exhaustive list of details about screens and GUI, input and input conditions, all system states and state changes, all persistent data, etc.

This 4th item is what we usually mean by a Software Requirements Specification (SRS) document

SWE513 Spring 2010 - UML tutorial Part I

17

Example: Automated Library System

Vision Statement
You have been contracted to develop a computer system for a university library. The library currently uses a 1960s program, written in an obsolete language, for some simple bookkeeping tasks, and a card index, for user browsing.You are asked to build an interactive system which handles both of these aspects online.

SWE513 Spring 2010 - UML tutorial Part I

18

Example: More Details on Needs

Books and Journals


Library contains books and journals Books may have several copies Some books are short-term loans, all others 3 weeks Only staff can borrow journals Members can borrow up to 6 items at a time Staff can borrow up to 12 items New items arrive, old items are disposed of Current years journals are bound at year-end
SWE513 Spring 2010 - UML tutorial Part I 19

Use Case Modeling

Use Case:
A sequence of actions a system performs to yield an observable result of value to a particular actor. Stevens/Pooley: A task which an actor needs to perform with the help of the system

Actor:
Someone or something outside the system that interacts with the system A user of the system in a particular role

Important: We want an external view of the system

SWE513 Spring 2010 - UML tutorial Part I

20

Use Cases

Each use case has a name


e.g. Borrow Copy of Book

A family (or set, or class) of scenarios


A sequence of interactions A set of different but related scenarios

Documenting Use Cases


A UML Diagram showing all of them Actors are stick-figures; use cases are ovals

For each use case define using English


A clear textual description A set of scenarios in outline form

SWE513 Spring 2010 - UML tutorial Part I

21

Example: Actors and Use Cases

Actors
BookBorrower JournalBorrower Browser (person who browses, not SW) Librarian Borrow copy of a book Reserve a book Return copy of book Borrow journal Browse Update Catalog
SWE513 Spring 2010 - UML tutorial Part I 22

Use Cases

What Form Does a Use Case Take?


We can describe Use Cases in a variety of ways First, text paragraphs Describes the Actors who participate with the system Describes the sequence of events

SWE513 Spring 2010 - UML tutorial Part I

23

Forms of Such Descriptions

Informal Scenarios
an informal narrative story, simple, natural, personal, not generalisable

Use cases

assume interaction with a system assume detailed understanding of the interaction


abstract away from the details does not have the same assumptions as use cases

Essential use cases


SWE513 Spring 2010 - UML tutorial Part I

24

Example Text Description

Borrow copy of a book:


A Bookborrower presents a copy of a book. The system checks that the s/he is a library member, and that s/he has not checked out too many books. If both checks succeed, then the system records that the member now as this copy of the book. Otherwise it refuses the loan.
SWE513 Spring 2010 - UML tutorial Part I 25

What Else Is In a Use Case Description?

Pre- and Post-conditions


Values of variables, system conditions, other use cases etc.

Normal vs. alternative behavior


Can be shown in the text description (somehow) Exceptions vs. acceptable alternatives

SWE513 Spring 2010 - UML tutorial Part I

26

Example Template for Use Cases


Use case number or id: Use case title: Actors: Text description (a few sentences) Preconditions (if applicable): Flow of Events: Basic path:
1.First step 2.Second step 3.etc

Alternative Paths:
Name and short description (in words) of first alternative path/scenario. Name and short description (in words) of 2nd alternative path/scenario. etc.

Postconditions (if applicable) Special conditions (if applicable).

SWE513 Spring 2010 - UML tutorial Part I

27

Scenario for shared calendar


The user types in all the names of the meeting participants together with some constraints such as the length of the meeting, roughly when the meeting needs to take place, and possibly where it needs to take place. The system then checks against the individuals calendars and the central departmental calendar and presents the user with a series of dates on which everyone is free all at the same time. Then the meeting could be confirmed and written into peoples calendars. Some people, though, will want to be asked before the calendar entry is made. Perhaps the system could email them automatically and ask that it be confirmed before it is written in.

SWE513 Spring 2010 - UML tutorial Part I

28

Use case for shared calendar


1. The user chooses the option to arrange a meeting. 2. The system prompts user for the names of attendees. 3. The user types in a list of names. 4. The system checks that the list is valid. 5. The system prompts the user for meeting constraints. 6. The user types in meeting constraints. 7. The system searches the calendars for a date that satisfies the constraints. 8. The system displays a list of potential dates. 9. The user chooses one of the dates. 10. The system writes the meeting into the calendar. 11. The system emails all the meeting participants informing them of them appointment

SWE513 Spring 2010 - UML tutorial Part I

29

Alternative paths for shared calendar


Step 5. If the list of people is invalid, then: 5.1 The system displays an error message. 5.2 The system returns to step 2.

Step 8.

If no potential dates are found, then 8.1 The system displays a suitable message. 8.2 The system returns to step 5.

SWE513 Spring 2010 - UML tutorial Part I

30

Example use case diagram for shared calendar


Arrange a meeting Retrieve contact details

Administrator Update calendar entry

Departmental member

SWE513 Spring 2010 - UML tutorial Part I

31

Essential use-case for arrangeMeeting useUse-case Name: arrangeMeeting


USER INTENTION 1. arrange a meeting 3. identify meeting attendees & constraints SYSTEM RESPONSIBILITY 2. request meeting attendees & constraints

6. choose preferred date

4. search calendars for suitable dates 5. suggest potential dates 7. book meeting

SWE513 Spring 2010 - UML tutorial Part I

32

Relationships between Use Cases

UML supports two relationships between two use cases


<<includes>> and <<extends>> Note: before UML 1.3 <<includes>> was <<uses>>

SWE513 Spring 2010 - UML tutorial Part I

33

<<includes>> in Use Cases

Meaning:
The source use case always includes the actions specified in the target use case

<<extends>> in Use Cases

Meaning:
The target use case my include the behavior of the source use case
SWE513 Spring 2010 - UML tutorial Part I 34

Back to business...
Enough on Requirements-Use Cases couple, back to core UML....

SWE513 Spring 2010 - UML tutorial Part I

35

UML Diagrams (recap...)

Functional Requirements
Use-Case (relationship between actors and system functions) Class (static class structure) Object (same as class - only using class instances i.e. objects) Package (logical grouping of classes) Component (code structure) Deployment/Implementation (mapping of software to hardware) State (states of objects in a particular class) Sequence (Object message passing structure) Collaboration/Communication (same as sequence but also shows context - i.e. objects and their relationships) Activity (sequential flow of activities i.e. action states)
SWE513 Spring 2010 - UML tutorial Part I 36

Structure

Behavior

The Class Diagram

SWE513 Spring 2010 - UML tutorial Part I

37

The Object Diagram

SWE513 Spring 2010 - UML tutorial Part I

38

Example: Library system


Library class hierarchy
Library item Catalo gue n umber Acquisition da te Cost T pe y Status Number of copies Acquire () Catalo gue () Dispose () Issue () Return ()

Pub lished item Title Pub lisher

Recorded item Title Medium

Book A uthor Edition Pub lication da te ISBN

Magazine Y ear Issue

Film Director Date of release Distrib utor

Computer pro gram V ersion Platfor m

SWE513 Spring 2010 - UML tutorial Part I

39

Example: Lib. User class hierarchy


Library user Name Address Phone Reg istration # Reg ister () De-reg ister ()

Reader Af filiation

Borrower Items on loan Max. loans

Staff Depar tment Depar tment phone

Student Major subject Home ad dress

SWE513 Spring 2010 - UML tutorial Part I

40

Multiple inheritance

Rather than inheriting the attributes and services from a single parent class, a system which supports multiple inheritance allows object classes to inherit from several super-classes. This can lead to semantic conflicts where attributes/services with the same name in different super-classes have different semantics. Multiple inheritance makes class hierarchy reorganisation more complex.

SWE513 Spring 2010 - UML tutorial Part I

41

Multiple inheritance
Book Author Edition Pub lication da te ISBN Voice recording Speak er Duration Recording da te

T alking book # Tapes

SWE513 Spring 2010 - UML tutorial Part I

42

Object aggregation
An aggregation model shows how classes that are collections are composed of other classes. Aggregation models are similar to the part-of relationship in semantic data models.

SWE513 Spring 2010 - UML tutorial Part I

43

Object aggregation

SWE513 Spring 2010 - UML tutorial Part I

44

Object behaviour modeling


A behavioural model shows the interactions between objects to produce some particular system behaviour that is specified as a use-case. Sequence diagrams (or collaboration diagrams) in the UML are used to model interaction between objects.

SWE513 Spring 2010 - UML tutorial Part I

45

Reminder: Analysis models


Earlier we modeled requirements using... Class Diagrams: Known as the Conceptual Model
Sometimes known as the logical model. Classes represent domain-level entities. (E.g. things in the users world.)
Thus no classes for implementation-level things.

Associations model domain-level relationships. (E.g. user-understood relationships between things in the users world.)
Usually dont show navigation on associations
SWE513 Spring 2010 - UML tutorial Part I 46

Reminder: Analysis models (2)

Use Cases and Sequence Diagrams


Scenarios in a Use Case can be represented by UML sequence diagrams Objects in the sequence diagram could be either:
The system and the actors, or... Domain-level entities modeled in the conceptual model (a class diagram)

Messages between objects are:


Again, at a high-level of abstraction Scenario descriptions become messages

SWE513 Spring 2010 - UML tutorial Part I

47

Reminder: Goals for design


Create detailed plans (like blueprints) for implementation Build these from requirements models so we are confident that all user needs will be met Create design models before coding so that we can:

Compare different possible design solutions Evaluate efficiency, ease of modification, maintainability, etc
SWE513 Spring 2010 - UML tutorial Part I 48

UML Notations for Design


Several UML notations provide various views of a design Class diagrams: Possibly created at two different levels of abstraction for design:

Two types of Interaction Diagrams:

Specification level: Classes model types, and we focus solely on interfaces between software modules Implementation level: Think of this as a true software blueprint. We can go directly to code from this model.
Sequence diagrams and Collaboration diagrams

SWE513 Spring 2010 - UML tutorial Part I

49

UML Notations for Design (2)

Sequence diagrams
Objects will be variables implemented in code Messages are operations (e.g. C++ member functions) applied to objects Sequence diagrams thus show how a sequence of operations called between a set of objects accomplishes a larger task Sequence diagrams for a particular scenario help identify operations needed in classes They also allow us to verify that a design can support requirements (e.g. a use-case scenario)
SWE513 Spring 2010 - UML tutorial Part I 50

UML Notations for Design (3)

State diagrams
Models how a particular object responds to messages according to its state For a single object, show states and transitions between states Transitions may be conditional based on a guard condition May show an action an object takes on transition, or also activity carried out within a state Occasionally used to model a systems or subsystems behavior (not just one objects)
SWE513 Spring 2010 - UML tutorial Part I 51

UML Notations for Design (4)

Packages
A simple notation that groups classes together Possible to use this to show contents of a subsystem
Show dependencies between packages Show visibility of classes between packages

Not really a rich enough notation for diagramming software architectures

Component Diagrams
Models physical modules of code (e.g. files, DLLs, physical databases)
SWE513 Spring 2010 - UML tutorial Part I 52

Design Process
There are many different approaches to design, but here is something typical. First, create a model of the high-level system architecture

UML does not really provide a notation this

Next, use the conceptual class model to build a design-level class model or models Also, model dynamic behavior using interaction diagrams.

Here well assume were just building an implementationlevel class model

SWE513 Spring 2010 - UML tutorial Part I

53

Design Process (contd)

Well use sequence diagrams with objects from the implementation-level class model
Sequence diagrams show how design-level objects will carry out actions to implement scenarios defined as part of use-case analysis Messages between objects are member-function calls between objects Important: Only member-function calls are shown, but other language statements (e.g. assignments) are executed between calls (of course).
SWE513 Spring 2010 - UML tutorial Part I 54

Design Process (contd)


Important: Development of class and sequence diagrams is iterative and concurrent When we create sequence diagrams for a new scenarios, we discover classes and operations that need to be added to the class model The two models grow together. Neither is a complete view of the system. Other documentation in text form is often used to provide details about class diagrams and sequence diagrams

SWE513 Spring 2010 - UML tutorial Part I 55

SpecificationSpecification-Level Class Diagrams

How does a design-level class diagram differ from a conceptual-level diagram?


No longer just an external view! We are now modeling how not just what.

This class diagram must document:


Additional classes How you will implement associations
Multiplicity, Navigability or Direction; Association classes
SWE513 Spring 2010 - UML tutorial Part I 56

Additional Classes in a Design

Are additional classes needed? Of course! In general... Design-level internal classes

Is there any guidance or strategy for determining these?


SWE513 Spring 2010 - UML tutorial Part I

Data manager classes. E.g. collection objects that were simply associations before Facilitator or helper classes that assist with complex tasks (e.g. ObservableComponent) Factory classes that assist in creating new objects Classes to implement other design patterns

57

Class Types in a Layered Architecture


5-layer model Classes only interact within layers, or as shown by arrows

User Interface Classes

Controller/ Process Classes System Classes Business/Domain Classes

Direction matters!

Next slide describes these

Persistence Classes

Persistent Store(s)
SWE513 Spring 2010 - UML tutorial Part I 58

Possible Design Class Types


UI classes Business/Domain classes

Implement domain-objects from Analysis Data objects plus their behaviors

Controller/Process classes
implement business logic, collaborations between business objects and/or other controller

Persistence classes
How to store, retrieve, delete objects Hides underlying data stores from rest of system

System classes
Wrap OS-specific functionality in case that changes
SWE513 Spring 2010 - UML tutorial Part I 59

Controller/Process Layer

Implements business logic


Encapsulate a business rule These often require interactions etc. between objects of different classes
Example from a student course enrollment system:

When can a Student enroll in a Seminar?


Depends on schedule, pre-requisites, other constraints

SWE513 Spring 2010 - UML tutorial Part I

60

More on Controllers

Why not just put business logic into the Domain class?
Business rules change. We want domain classes to be reusable. In UI class? Then must use that UI to carry out this process. (Too tightly coupled.)

How to find Controller classes?


To start: consider one for each use-case If trivial or belongs in domain class, dont.
SWE513 Spring 2010 - UML tutorial Part I 61

Controller Classes: Good OO?


Violates a principle of the OO approach! Yes, but is this always the best solution?
Data and behavior kept together!
DVDs and DVD players -- why not one unit? Cameras and film vs. disposable cameras

Consider coupling, change, flexibility Controller classes are an example of the Mediator design pattern Mediator or control classes might grow to become god classes
too much control, or too centralized
SWE513 Spring 2010 - UML tutorial Part I

62

Implementing Associations
How associations are implemented is affected by multiplicity. Where they are implemented depends on navigability.

In one class or in both? Until now we may not have worried about direction of associations. Thats fine! Often navigability cannot be determined until design phase. Often it changes as we do more design. In prototypes we often keep links bidirectional for flexibility.

SWE513 Spring 2010 - UML tutorial Part I

63

Implementing Associations (2)

Often we use class operations to hide implementation details of associations


getters, setters, traversal functions, update functions, etc. Also, derived associations (or attributes) are implemented as member functions that calculate something that is not stored directly in the class.

SWE513 Spring 2010 - UML tutorial Part I

64

OneOne-Way Associations

If an association should just be navigable in just one direction, use the arrow form of the UML association in your class diagram.
In UML no arrows means two-way or bi-directional.

For implementation, the target object becomes an attribute in the class


In C++, it could be stored as an embedded object or as a pointer In Java, objects are always references variables (so embedded objects really are pointers)

Consider using association name or role name from the class diagram to name this attribute

SWE513 Spring 2010 - UML tutorial Part I

65

Multiplicity and One-Way Associations One

If the multiplicity is 1 or 0..1 then the attribute would be a pointer to an object of the target class
E.g. attribute in class Phone: E.g. 3, 0..3, 2..4 selectedLine: Line*

If the multiplicity is many but has a fixed maximum, then use array of pointers (or objects)

If no fixed maximum, e.g. 1..* or 0..*, then use a collection object as an attribute that stores an arbitrarily large number of pointers or objects For qualified associations use a hash-table or map object to associate key with target object

SWE513 Spring 2010 - UML tutorial Part I

66

Multiplicity and One-Way Assoc. (2) One

Examples using the C++ standard library... A vector class is like an array with no maximum capacity Other C++ classes might be appropriate too: set, list Note: Your team might agree not to show the * to indicate pointers. Conventions vary.
SWE513 Spring 2010 - UML tutorial Part I 67

Example attribute in class Phone: linkedLines: vector<Line*>

Arrays should only be used if you know the maximum

Implementing Two-Way Associations Two

Three options, depending on your needs


Note: Sometimes its OK if traversal in one direction is slower than the other

Option One: Just like one-way but in both classes


Advantages: Equally efficient in both directions But, requires more space Also, updating links between objects is more complex
Often a good idea to use member functions to handle updates to links.
SWE513 Spring 2010 - UML tutorial Part I 68

Implementing Two-Way Assoc. (2) Two

Option Two:
In one class, Class A, implement just like oneway (see above) to access Class B objects. In second class, Class B, write an operation that uses some kind of search of all objects of Class A to find the one that points back to the current B object.
Why? Saves space if access from B to A is very rare But, requires there to be some place where all objects of Class A are stored
SWE513 Spring 2010 - UML tutorial Part I 69

Implementing Two-Way Assoc. (3) Two

Option Three: Implement an Association Class


This class will have only one instance, which stores all the links between objects of the two classes Implemented as two dictionary or map objects
One points to Class A objects, the other to Class B objects

Search of this object is used to find links for one object

SWE513 Spring 2010 - UML tutorial Part I

70

Example of Assoc. Object


A person works for one company. A company has many employees. If pointers are not bi-directional, then Works-For object must support efficient look-up of a Person object in order to find that objects company. Note: This is not a UML diagram!

Works-For Person1 Person2 Company1

Person3
SWE513 Spring 2010 - UML tutorial Part I

Company2
71

Flashback to previous slides

Lets look at class diagrams now.

SWE513 Spring 2010 - UML tutorial Part I

72

Association Classes
Recall that qualified associations really mean that the link between two objects has an attribute Often associations are first-class things

They have a life-time, state, and maybe operations Just like objects!

Association classes
Same name as the association because... They represent the same thing!
SWE513 Spring 2010 - UML tutorial Part I 73

Association Class Example


Company 0..* employer

Job description : string dateHired : Date salary : Money

employee 1..* Person

SWE513 Spring 2010 - UML tutorial Part I

74

World Cup Example


We need a system to handle the World Cup. Teams represent countries and are made up of 22 players. Countries qualify from zones, where each zone is either a country or a group of countries. Each team plays a given number of games in a specific city. Referees are assigned to games. Hotel reservations are made in the city where the teams play.

SWE513 Spring 2010 - UML tutorial Part I 75

World Cup Problem: Class Model


R es e epr nts
0 1

Team 2 * Qualifying Unit 22 Player 1 Country 1 Represents 3 Zone


1

Hotel Reservation

*
3

Play
Pla n ysI
2

s at

City

Referee

*
Assignment

*
Game

SWE513 Spring 2010 - UML tutorial Part I

76

Implementing Association Classes


Implementation depends on multiplicity If one-to-one, then it would be possible to...

If one-to-many, then same choices as one-toone, but do this for the object on the many end If many-to-many, you need a separate class with an object instantiated for each link
SWE513 Spring 2010 - UML tutorial Part I

Put attributes and operations inside either object Or, put them in a separate class thats linked to either object

Again, could be a separate object (see next case)

77

Example of Association Class Implementation

Conceptual-Level Class Diagram


0..1 ClassA 1..* ClassB

AssocClass

Corresponding Design-Level Class Diagram


ClassA 1 1..* AssocClass 0..1 1 ClassB

SWE513 Spring 2010 - UML tutorial Part I

78

Notes on Example Implementation


No direct link (pointer) in design or implementation between ClassA and ClassB instances! But... Each instance of an AssocClass object is linked to exactly one ClassA object and also to one ClassB object

This forms a 3-tuple for each conceptual-level link between a pair of ClassA and ClassB objects

Note multiplicities reflect concept level:


One ClassA object is linked to 1-to-many AssocClass/ClassB pairs. Great! One ClassB object links to 0-or-one AssocClass/ClassA pairs. Yes!

SWE513 Spring 2010 - UML tutorial Part I

79

Next week Part 2 ...


Some more on UML Some case studies/examples UML tools: Eclipse UML plugins, MS Visio, Rational Software Architect, others Project announcement

SWE513 Spring 2010 - UML tutorial Part I

80

Thanks :-) :See you next week! http://www.cmpe.boun.edu.tr/~gur Email : gurgurka@boun.edu.tr

SWE513 Spring 2010 - UML tutorial Part I

81

Unified Modeling Language


SWE 513 UML tutorial Part II
Grkan Gr

Agenda
Some more on UML (especially interaction diagrams) Some case studies/examples UML tools: Eclipse UML plugins, MS Visio, Rational Rose, others Project announcement

SWE513 Spring 2010 - UML tutorial Part II

83

UML Diagrams (recap...)

Functional Requirements
Use-Case (relationship between actors and system functions) Class (static class structure) Object (same as class - only using class instances i.e. objects) Package (logical grouping of classes) Component (code structure) Deployment/Implementation (mapping of software to hardware) State (states of objects in a particular class) Sequence (Object message passing structure) Collaboration/Communication (same as sequence but also shows context - i.e. objects and their relationships) Activity (sequential flow of activities i.e. action states)
SWE513 Spring 2010 - UML tutorial Part I 84

Structure

Behavior

Dynamic Views in UML

Class diagrams are models of data types


What non-fundamental types are you using? How are they related? Sometimes referred to as the static model

Running programs define objects of various types that interact


Control is passed between objects methods Information is passed and returned

UML has two almost identical diagrams for this:


Collaboration diagram: object-centered Sequence diagram: time-oriented

Important: Each diagram models a particular scenario


Often we just model important or interesting scenarios

SWE513 Spring 2010 - UML tutorial Part II

85

Sequence Diagram -1

SWE513 Spring 2010 - UML tutorial Part II

86

Sequence Diagram-2: issue of Diagram- issue electronic items

SWE513 Spring 2010 - UML tutorial Part II

87

Sequence Diagram-3 Diagram-

SWE513 Spring 2010 - UML tutorial Part II

88

Collaboration Diagram-1 Diagram-

SWE513 Spring 2010 - UML tutorial Part II

89

Class Diagram with a Related Collaboration

SWE513 Spring 2010 - UML tutorial Part II

90

Activity Diagram

SWE513 Spring 2010 - UML tutorial Part II

91

Activity Diagram-2 Diagram-

Activity diagram showing behaviour of a thought process of how to play chess (badly)
SWE513 Spring 2010 - UML tutorial Part II 92

Sequence Diagram - 4

SWE513 Spring 2010 - UML tutorial Part II

93

Relationship Between Both Notations


collaboration diagram

sequence diagram

SWE513 Spring 2010 - UML tutorial Part II

94

Collaboration Diagram - 2

SWE513 Spring 2010 - UML tutorial Part II

95

Sequence Diagram-5 Diagram-

SWE513 Spring 2010 - UML tutorial Part II

96

Use Cases and Sequence Diagrams


So far sequence diagrams model interactions between implementation-level objects Also, can be used to model use cases
Actor(s) interacting with the System
Most useful if more than one Actor Messages are used informally here

Example: ATM customer tries to overdraw

Also, sequence diagrams sometimes used in high-level design


model interactions between major subsystems

SWE513 Spring 2010 - UML tutorial Part II

97

Iteration, Control, Return Values


Messages can be labeled with a condition: [hasStock] sellWidget() Messages can be repeated: * msg() or *[k=1..2] msg() Return values:

Maybe on dashed return arrow, or On message call: n = getName() Again, note returns not always explicitly drawn
SWE513 Spring 2010 - UML tutorial Part II 98

Notes on Messages

Various types of messages supported


Filled solid arrow head: Half arrow head: Dashed arrow:
like procedure calls, nested flow of control. Caller waits for action to complete. Asynchronous flow of control. Caller is not blocked, continues to do something. Return from procedure call. May be omitted if its implicit at end of an activation box

Use stereotypes to define anything else.


SWE513 Spring 2010 - UML tutorial Part II

99

Iterations, Constraints, Asynch. Messages Asynch.

SWE513 Spring 2010 - UML tutorial Part II

100

Phone Switch Example

Optional for class lecture

SWE513 Spring 2010 - UML tutorial Part II

101

Phone Switch Example

Classes Phone: a persons telephone Line: a number associated with a phone Lines are busy, calls are made on lines, etc. Connection: dynamically created, represents an active call between lines Switch: a phone switch is a computer system that manages phones, lines and connections Console: a terminal attached to the switch Simulator: were writing a simulation!

SWE513 Spring 2010 - UML tutorial Part II

102

Associations in Our Model


Switch manages other objects More than one Phone may be linked to one line
Like for office secretary, boss

A Phone may have more than one Line


Must choose a Line to call or answer

But, a Phone has only one Line selected at one time


Also, when a Line is connected, not all Phones that can possibly use that Line may be participating in the call.

A Connection requires at least two Lines to exist

SWE513 Spring 2010 - UML tutorial Part II

103

Conceptual Class Diagram


Simulator 1 1 controls manages 1 controls 1 Switch name : string 1 manages 1 manages 0..* Connection id : int state : ConnState duration : int 0..1

0..*

Phone state : PhoneState name : string

0..*0..*

selected

0..* Line 1 number : string state : LineState 2..* 1

0..* onConnection 1..*

link edLines 1..*

SWE513 Spring 2010 - UML tutorial Part II

104

Scenario

A normal call
Phone1 chooses Line 1 and picks up Phone 1 dials number for Phone2 Phone 2 rings Phone 2 picks up Call completed and the two people talk Phone 2 hangs up Phone 1 is disconnected Phone 1 hangs up
SWE513 Spring 2010 - UML tutorial Part II 105

Class Diagram with Operations


Simulator
controls processCmds(in : istream)

Switch
name : string

1 getPhone(name : string) : Phone


getLine(number : string) : Line addLine(num : String) : void addPhone(p : Phone) : void linkLinePhone(name : string, num : int) : void newCall(l1 : Line, l2 : Line) : void completeConn(l : Line, c : Connection) : void destroyConn(c : Connection) : void

1
controls

1
manages

1
manages

1
manages

0..* Phone
state : PhoneState name : string

0..*
0..*

0..* Connection
id : int state : ConnState duration : int disconnect(l : Line) : void addLine(l : Line) : void

0..*

Line selected number : int 1


state : LineState

selectLine(num : int) : void pickup() : void hangup() : void ring() : void dial(num : int) : void addLine(l : Line) : void

incomingCall(c : Connection) : void hungUp(p : Phone) : void linkedLines 1..* pickedUp(p : Phone) : void 0..* addPhone(p : Phone) : void

onConnection 1..*

2..* 1

0..1

SWE513 Spring 2010 - UML tutorial Part II

106

Sequence Diagram for a Normal Phone Call


s: Simulator p1: Phone s:Switch l1: Line c1: Connection l2: Line p2: Phone selectLine(n) pickup() pickedUp(p1) dial(num) l2 := getLine(num) newCall(l1, l2) <<create>> (l1) incomingCall(c1) ring()

pickup() completeConn(l2,c1) addLine(l2)

pickedUp(p2)

hangup() destroyConn(c1) /* change state */ <<destroy>> disconnect(l2) hungUp(p2)

hangup() hungup(p1)

SWE513 Spring 2010 - UML tutorial Part II

107

UML Diagrams (recap...)

Functional Requirements
Use-Case (relationship between actors and system functions) Class (static class structure) Object (same as class - only using class instances i.e. objects) Package (logical grouping of classes) Component (code structure) Deployment/Implementation (mapping of software to hardware) State (states of objects in a particular class) Sequence (Object message passing structure) Collaboration/Communication (same as sequence but also shows context - i.e. objects and their relationships) Activity (sequential flow of activities i.e. action states)
SWE513 Spring 2010 - UML tutorial Part II 108

Structure

Behavior

Less Common Diagrams : Package Diagram


A package is a UML construct that enables you to organize model elements, such as use cases or classes, into groups. Packages are depicted as file

folders and can be applied on any


UML diagram. Class Package diagrams

Use Case package diagrams

SWE513 Spring 2010 - UML tutorial Part II

109

Less Common Diagrams : Component Diagram


Issue of electronic items

SWE513 Spring 2010 - UML tutorial Part II

110

Less Common Diagrams : Deployment Diagram

SWE513 Spring 2010 - UML tutorial Part II

111

Enough with standard UML narrative, something different ...

Optional for class lecture

The next part is from Patterns, Frameworks and Middleware: Their Synergestic Relationships tutorial by D. C. Schmidt: http://www.cs.wustl.edu/~schmidt/tutorialspatterns.html (a very important source for serious distributed networked software design and development)

SWE513 Spring 2010 - UML tutorial Part II

112

Idioms, Patterns, Frameworks


Idiom: a small language-specific pattern or technique


A more primitive building block

Design pattern: a description of a problem that reoccurs and an outline of an approach to solving that problem
Generally domain, language independent Also, analysis patterns

Framework:
A partially completed design that can be extended to solve a problem in a domain
Horizontal vs. vertical

113

Taxonomy of Patterns & Idioms


Type Description Examples

Idioms
Design patterns

Restricted to a particular language, system, or tool


Capture the static & dynamic roles & relationships in solutions that occur repeatedly Express a fundamental structural organization for software systems that provide a set of predefined subsystems, specify their relationships, & include the rules and guidelines for organizing the relationships between them Document rules for avoiding common design & implementation mistakes that degrade performance

Scoped locking
Active Object, Bridge, Proxy, Wrapper Faade, & Visitor Half-Sync/HalfAsync, Layers, Proactor, PublisherSubscriber, & Reactor Optimize for common case, pass information between layers

Architectural patterns

Optimization principle patterns

114

Example: Boeing Bold Stroke


Nav Sensors Vehicle Mgmt

Mission Computer

Data Links

Weapon Management

Radar Weapons

Bold Stroke Architecture

Mission Computing Services Middleware Infrastructure Operating System Networking Interfaces Hardware (CPU, Memory, I/O)

Avionics mission computing product-line

architecture for Boeing military aircraft, e.g., operating systems, & middleware F-18 E/F, 15E, Harrier, UCAV Used as Open Experimentation DRE system with 100+ developers, 3,000+ Platform (OEP) for DARPA IXO PCES, software components, 3-5 million lines of MoBIES, SEC, MICA programs 115 C++ code

Based on COTS hardware, networks,

Example: Boeing Bold Stroke


Mission Computing Services Middleware Infrastructure

Operating System
Networking Interfaces Hardware (CPU, Memory, I/O)

COTS & Standards-based Middleware Infrastructure, OS, Network, & Hardware Platform
Real-time CORBA middleware services VxWorks operating system VME, 1553, & Link16 PowerPC
116

Example: Boeing Bold Stroke


Reusable Object-Oriented Application Domain-specific Middleware Framework
Configurable to variable infrastructure configurations Supports systematic reuse of mission computing functionality

Mission Computing Services Middleware Infrastructure Operating System Networking Interfaces Hardware (CPU, Memory, I/O)

117

Example: Boeing Bold Stroke


Product Line Component Model
Configurable for product-specific functionality & execution environment Single component development policies Standard component packaging mechanisms

Mission Computing Services Middleware Infrastructure Operating System Networking Interfaces Hardware (CPU, Memory, I/O)

118

Example: Boeing Bold Stroke

Mission Computing Services Middleware Infrastructure Operating System Networking Interfaces Hardware (CPU, Memory, I/O)

Component Integration Model

Operator
Real World Model

Configurable for product-specific component assembly & deployment environments Model-based component integration policies

Avionics Interfaces

Infrastructure Services

119

Examples of C++ Idioms

Use of an Init() function in constructors


If there are many constructors, make each one call a private function Init() Init() guarantees all possible attributes are initialized Initialization code in one place despite multiple constructors

Dont do real work in a constructor


Define an Open() member function Constructors just do initialization Open() called immediately after construction Constructors cant return errors They can throw exceptions

120

Design Patterns: Essential Elements


Pattern name
A vocabulary of patterns is beneficial

Problem
When to apply the pattern, what context. How to represent, organize components Conditions to be met before using

Solution
Design elements: relationships, responsibilities, collaborations A template for a solution that you implement

Consequences
Results and trade-offs that result from using the pattern Needed to evaluate design alternatives

121

Patterns Are (and Arent)


Name and description of a proven solution to a problem Documentation of a design decision Theyre not:

Reusable code, class libraries, etc. (At a higher level) Do not require complex implementations Always the best solution to a given situation Simply a good thing to do

122

Describing Design Patterns

The GoF (Design Patterns: Elements of Reusable Object-Oriented Software) defined a standard format
Generally followed Not just a UML diagram!

Pattern Format (13 sections):


Pattern name and classification Intent: whats it do? Rationale? Also known as Motivation A scenario that illustrates a sample problem and how this patterns helps solve it. Applicability For which situations can this be applied? Structure Graphical representation (e.g. UML)
123

Pattern Format (contd)


Participants Classes and objects, their responsibilities Collaborations How participants interact Consequences Implementation Pitfalls, hints, techniques, language issues Sample code Code fragments that illustrate the pattern Known uses From real systems Related patterns Similar patterns, collaborating patterns

124

Example 1: Singleton Pattern


Context: Only one instance of a class is created. Everything in the system that needs this class interacts with that one object. Controlling access: Make this instance accessible to all clients Solution:

The class has a static variable called theInstance (etc) The constructor is made private (or protected) Clients call a public operation getInstance() that returns the one instance This may construct the instance the very first time or be given an initializer

125

Singleton: Java implementation


public class MySingleton { private static MySingleton theInstance =

new MySingleton();
private MySingleton() { // constructor } public static MySingleton getInstance() { return theInstance; } }
126

Static Factory Methods


Singleton patterns uses a static factory method


Factory: something that creates an instance

Advantages over a public constructor


They have names. Example: BigInteger(int, int, random) vs. BigInteger.probablePrime() Might need more than one constructor with same/similar signatures Can return objects of a subtype (if needed)

Wrapper class example: Double d1 = Double .valueOf(3.14); Double d2 = new Double (3.14);

127

The State Design Pattern

A connection can be in various states


Which changes dynamically

Handles requests differently depending on state

Connection delegates requests to its state object

128

Some UML Tools


Rational eUML

Rose Family

Eclipse Plugin

MS Visio

SWE513 Spring 2010 - UML tutorial Part II

129

Rational Rose Family

130

Rational Rose Family (cont.)

131

eUML2

132

eUML2 (cont.)

133

Generated from the Appender interface to display its inheritance & ass. relationships ass.

134

A sequence diagram generated automatically from a method

135

Thanks :-) :http://www.cmpe.boun.edu.tr/~gur Email : gurgurka@boun.edu.tr

SWE513 Spring 2010 - UML tutorial Part II

136

Anda mungkin juga menyukai