Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 2: Introduction to UML

Similar presentations


Presentation on theme: "Module 2: Introduction to UML"— Presentation transcript:

1 Module 2: Introduction to UML
Background What is UML for? Building blocks of UML UML Diagrams

2 References Documentation on UML is available from:
Rational Rose is available from: Visual Modeling with Rational Rose and UML, Terry Quatrani, 1998.

3 Overview Background What is UML for? Building blocks of UML
Process for Using UML

4 What is UML? The Unified Modelling Language is a standard graphical language for modelling object oriented software At the end of the 1980s and the beginning of 1990s, the first object-oriented development processes appeared The proliferation of methods and notations tended to cause considerable confusion Two important methodologists Rumbaugh and Booch decided to merge their approaches in 1994. They worked together at the Rational Software Corporation In 1995, another methodologist, Jacobson, joined the team His work focused on use cases In 1997 the Object Management Group (OMG) started the process of UML standardization

5 What is UML? The Unified Modeling Language (UML) is a language for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling.

6 ~ U ~ M L ~ Unified: Unifies all existing previous Notations Modeling:
Used for Modeling Software Artifacts L ~ Language: Means of Communication

7 UML is a language for: Visualizing: Graphical models with precise semantics Specifying: Models are precise, unambiguous and complete to capture all important Analysis, Design, and Implementation decisions. Constructing: Models can be directly connected to programming languages, allowing forward and reverse engineering Documenting: Diagrams capture all pieces of information collected by development team, allowing to share and communicate the embedded knowledge.

8 Unified Modeling Language (UML)
An effort by IBM (Rational) – OMG to standardize OOA&D notation Combine the best of the best from Data Modeling (Entity Relationship Diagrams); Business Modeling (work flow); Object Modeling Component Modeling (development and reuse - middleware, COTS/GOTS/OSS/…:) Offers vocabulary and rules for communication Not a process but a language Redun; simpler de facto industry standard

9 UML History OO languages appear mid 70’s to late 80’s
Between ’89 and ’94, OO methods increased from 10 to 50. Unification of ideas began in mid 90’s. Rumbaugh joins Booch at Rational ’94 v0.8 draft Unified Method ’95 Jacobson joins Rational ’95 UML v0.9 in June ’96 UML 1.0 offered to OMG in January ’97 UML 1.1 offered to OMG in July ’97 Maintenance through OMG RTF UML 1.2 in June ’98 UML 1.3 in fall ’99 UML 1.5 UML 2.0 underway Rational now has Grady Booch - Fusion James Rumbaugh – Object Modeling Technique (OMT) Ivar Jacobson – Object-oriented Software Engineering: A Use Case Approach (Objectory) ( And David Harel - StateChart)

10 UML is for Visual Modeling
A picture is worth a thousand words! - standard graphical notations: Semi-formal - for modeling enterprise info. systems, distributed Web-based applications, real time embedded systems, … Sales Representative Places Order Customer Fulfill Order Item Business Process via Ships the Item - Specifying & Documenting: models that are precise, unambiguous, complete UML symbols are based on well-defined syntax and semantics. analysis, architecture/design, implementation, testing decisions. - Construction: mapping between a UML model and OOPL.

11 UML is also for … Specifying Constructing Documenting
building models that are: Precise, Unambiguous, Complete UML symbols are based on well-defined syntax and semantics. UML addresses the specification of all important analysis, design, and implementation decisions. Constructing Models are related to OO programming languages. Round-trip engineering requires tool and human intervention to avoid information loss Forward engineering — direct mapping of a UML model into code. Reverse engineering — reconstruction of a UML model from an implementation. Documenting Architecture, Requirements, Tests, Activities (Project planning, Release management)

12 Three (3) basic building blocks of UML (cf. Harry)
Water have Fresh water Rivers Oceans have have Salt water live in have Fish have Crocodiles Penguins Things - important modeling concepts Relationships - tying individual things Diagrams - grouping interrelated collections of things and relationships Just glance thru for now

13 3 basic building blocks of UML - Things
UML 1.x Structural — nouns/static of UML models (irrespective of time). Behavioral — verbs/dynamic parts of UML models. Grouping — organizational parts of UML models. Annotational — explanatory parts of UML models. Main

14 <<interface>>
Structural Things in UML- 7 Kinds (Classifiers) Nouns. Conceptual or physical elements. Interface Node Active Class (processes/threads) Component (collection of externally Visible ops) Class (replaceable part, realizes interfaces) (computational resource at run-time, processing power w. memory) Event Mgr thread time Start suspend( ) stop( ) Student std_id grade changeLevel( ) setGrade( ) getGrade( ) Course.cpp IGrade <<interface>> IGrade UnivWebServer setGrade() getGrade() Manage Course Registration Register for Courses Use Case Collaboration (chain of responsibility shared by a web of interacting objects, structural and behavioral) (a system service sequence of Interactions w. actor)

15 <<interface>>
Structural Things in UML name attributes operations Window 1. Class A description of a set of objects that share the same attributes, operations, relationships, and semantics. Usually implements one or more interfaces. Cf. Active Class origin size open() close() 2. Interface A collection of operations that specify a service (for a resource or an action) of a class or component. It describes the externally visible behavior of that element. <<interface>> IWindow IWindow name operations open() close()

16 Structural Things in UML
3. Collaboration Chain of Responsibility Define an interaction among a web of objects. Define a society of roles and other elements. Provide cooperative behavior. Capture structural and behavioral dimensions. Order validation Order management <<refine>> 4. Use Case A sequence of actions that produce an observable result for a specific actor. Provides a structure for behavioral things. Realized through a collaboration (usually realized by a set of actors and the system to be built). Place Order

17 Structural Things in UML
5. Active Class Event Manager name attributes operations Special class whose objects own one or more processes or threads. Can initiate control activity. Thread time Heavy border suspend() flush() 6. Component Replaceable part of a system. Components can be packaged logically. Conforms to a set of interfaces. Provides the realization of an interface. Orderform.java 7. Node Element that exists at run time. Represents a computational resource. Generally has memory and processing power. WebServer Variations on Structural Things: Actors, Signals, Utilities, Processes & Threads, Applications, Documents, etc.

18 Behavioral Things in UML
Verbs. Dynamic parts of UML models: “behavior over time” Usually connected to structural things. Two primary kinds of behavioral things: Interaction a set of objects exchanging messages, to accomplish a specific purpose. harry: Student ask-for-an-A katie: Professor name = “Harry Kid” name = “Katie Holmes” State Machine specifies the sequence of states an object or an interaction goes through during its lifetime in response to events. received-an-A/ buy-beer inStudy inParty sober/turn-on-PC

19 Grouping Things in UML Packages - one primary kind of grouping.
- General purpose mechanism for organizing elements into groups. - Purely conceptual; only exists at development time. - Contains behavioral and structural things. - Can be nested. - Variations of packages are: Frameworks, models, & subsystems. Meeting Scheduler

20 Annotational Things in UML
Explanatory parts of UML models Comments regarding other UML elements (usually called adornments in UML) Note is one primary annotational thing in UML best expressed in informal or formal text. flexible drop-out dates

21 Grouping Things in UML: Packages
- For organizing elements (structural/behavioral) into groups. - Purely conceptual; only exists at development time. - Can be nested. - Variations of packages are: Frameworks, models, & subsystems. University Administration Course Manager Course Manager Student Admission -Student +Department Annotational Things in UML: Note - Explanatory/Comment parts of UML models - usually called adornments - Expressed in informal or formal text. flexible drop-out dates operation() {for all g in children g.operation() }

22 3 basic building blocks of UML - Relationships
4 Kinds Dependency Association Generalization Realization

23 Relationships in UML 1. Dependency 2. Associations Aggregation
a semantic relationship between two things in which a change to one thing (independent) may affect the semantics of the other thing (dependent). Directed is optional and label is optional. 2. Associations a structural relationship that describes a set of links, a link being a connection between objects. Can be directed labels Can have multiplicity & role names employer employee 0..1 * Aggregation a special kind of association. It represents a structural relationship between the whole and its parts. Represented by a diamond.

24 Relationships in UML 3. Generalization 4. Realization Where?
a specialization/generalization relationship in which objects of the specialized element (the child) are more specific than the objects of the generalized element. 4. Realization a semantic relationship between two elements, wherein one element guarantees to carry out what is expected by the other element. Where? Between interfaces and classes that realize them… Between use cases and the collaborations that realize them...

25 3 basic building blocks of UML - Relationships
Student University attends 1. Associations Structural relationship that describes a set of links, a link being a connection between objects. variants: aggregation & composition Student Person 2. Generalization a specialized element (the child) is more specific the generalized element. Student 3. Realization one element guarantees to carry out what is expected by the other element. (e.g, interfaces and classes/components; use cases and collaborations) IGrade Student harry: Student <<instanceOf>> 4. Dependency a change to one thing (independent) may affect the semantics of the other thing (dependent). (direction, label are optional)

26 3 basic building blocks of UML - Diagrams
A connected graph: Vertices are things; Arcs are relationships/behaviors. UML 1.x: 9 diagram types. UML 2.0: 12 diagram types Structural Diagrams Represent the static aspects of a system. Class; Object Component Deployment Structural Diagrams Class; Object Component Deployment Composite Structure Package Behavioral Diagrams Use case Statechart Activity Interaction Diagrams Sequence; Communication Interaction Overview Timing Behavioral Diagrams Represent the dynamic aspects. Use case Sequence; Collaboration Statechart Activity

27 UML diagrams Class diagrams describe classes and their relationships
Interaction diagrams show the behaviour of systems in terms of how objects interact with each other State diagrams and activity diagrams show how systems behave internally Component and deployment diagrams show how the various components of systems are arranged logically and physically

28 Diagrams in UML – University Registration System as a Running Example
The SMU wants to computerize its registration system The Registrar sets up the curriculum for a semester One course may have multiple course offerings Students select four (4) primary courses and two (2) alternate courses Once a student registers for a semester, the billing system is notified so the student may be billed for the semester Students may use the system to add/drop courses for a period of time after registration Professors use the system to set their preferred course offerings and receive their course offering rosters after students register Users of the registration system are assigned passwords which are used at logon validation

29 Diagrams in UML – Actors in Use Case Diagram
An actor is someone or some thing that must interact with the system under development Professor Registrar Student Billing System

30 Diagrams in UML - Use Cases in Use Case Diagram
A use case is a pattern of behavior the system exhibits Each use case is a sequence of related transactions performed by an actor and the system in a dialogue Actors are examined to determine their needs Registrar -- maintain the curriculum Professor – set course offerings and request roster Student -- register for courses Billing System -- receive billing information from registration Maintain Curriculum Request Course Roster Register for Courses

31 Diagrams in UML - Use Case Diagram
Use case diagrams are created to visualize the relationships between actors and use cases Request Course Roster Professor Student Set Course Offerings Register for Courses Billing System Maintain Curriculum Registrar Duplication?

32 Diagrams in UML - Documenting Use Cases in Use Case Diagram
A flow of events is described in documents for each use case Written from an actor point of view Details what the system must provide to the actor when the use case is executed Typical contents How the use case starts and ends Normal flow of events Alternate flow of events Exceptional flow of events

33 Diagrams in UML – Flow of Events for Maintaining Curriculum and Setting Course Offerings
(Maintaining Curriculum and Setting Course Offerings are two of the activities in running university registration system) Flow of Events for Maintaining Curriculum Registrar Maintain Schedule This use case begins when the Registrar logs onto the Registration System and enters his/her password. The system verifies that the password is valid and prompts the Registrar to select the current semester or a future semester. The Registrar enters the desired semester. Flow of Events for Setting Course Offerings The system prompts the professor to select the desired activity: ADD, DELETE, REVIEW, or QUIT. If the activity selected is ADD: Add a Course subflow is performed. If the activity selected is DELETE: Delete a Course subflow is performed. If the activity selected is REVIEW: Review Curriculum subflow is performed. If the activity selected is QUIT, the use case ends. Set Course Offerings Professor

34 Diagrams in UML - Uses and Extends Use Case Relationships in Use Case Diagram
A uses relationship shows behavior common to one or more use cases An extends relationship shows optional behavior <<uses>> <<extends>> Register for courses <<uses>> Register for Distance Learning courses Logon validation Maintain curriculum

35 Diagrams in UML - Use Case Realizations
A use case diagram presents an outside view of the system. Then, how about the inside view of the system? Interaction diagrams describe how use cases are realized as interactions among societies of objects, including the messages that may be dispatched among them. They address the dynamic view of the system. Two types of interaction diagrams Sequence diagrams Collaboration diagrams Execution of these two concurrent substates continues in parallel.

36 Diagrams in UML - Sequence Diagram
A sequence diagram displays object interactions arranged in a time sequence registration registration : Student math 101 math 101 form manager section 1 1: fill in info 2: submit 3: add course(Sue, math 01) 4: are you open? 5: are you open? 6: add (Sue) 7: add (Sue) Which use case is this for?

37 Diagrams in UML - Collaboration Diagram
Displays object interactions organized around objects and their direct links to one another. Emphasizes the structural organization of objects that send and receive messages. course form : 1: set course info CourseForm 2: process 3: add course : Registrar theManager : aCourse : CurriculumManager Course 4: new course Which use case is this for?

38 Diagrams in UML - Class Diagrams
A class diagram shows the existence of classes and their relationships in the logical view of a system UML modeling elements in class diagrams Classes and their structure and behavior Association, aggregation, dependency, and inheritance relationships Multiplicity and navigation indicators Role names

39 Diagrams in UML - Classes
A class is a collection of objects with common structure, common behavior, common relationships and common semantics Some classes are shown through the objects in sequence and collaboration diagram A class is drawn as a rectangle with three compartments Classes should be named using the vocabulary of the domain Naming standards should be created e.g., all classes are singular nouns starting with a capital letter

40 Diagrams in UML - Classes: Naming & 3 Sections
ScheduleAlgorithm RegistrationForm RegistrationManager Course Student Professor CourseOffering Which sequence/collaboration diagram are these from?

41 Diagrams in UML – Classes: Operations & Attributes
The behavior of a class is represented by its operations Operations may be found by examining interaction diagrams registration registration RegistrationManager addCourse(Student,Course) form manager 3: add course(Sue, math 01) Attributes The structure of a class is represented by its attributes Attributes may be found by examining class definitions, the problem requirements, and by applying domain knowledge CourseOffering number location time Each course offering has a number, location and time

42 Diagrams in UML – Some Classes with Operations & Attributes
ScheduleAlgorithm RegistrationForm RegistrationManager addStudent(Course, StudentInfo) Course name numberCredits open() addStudent(StudentInfo) Student name major Professor name tenureStatus CourseOffering location open() addStudent(StudentInfo)

43 Diagrams in UML – Object Diagrams
Shows a set of objects and their relationships. A static snapshot of instances. Harry (Student) Name: “Harry Mat” Major: CS Sue (Professor) Name: “Sue Becker” tenureStatus: true

44 Diagrams in UML – Finding Relationships
Relationships are discovered by examining interaction diagrams If two objects must “talk” there must be a pathway for communication RegistrationManager Course Registration Manager Math 101: Course 3: add student(Sue)

45 Diagrams in UML – Relationships: Multiplicity and Navigation
RegistrationForm RegistrationManager Course Student CourseOffering Professor addStudent(Course, StudentInfo) name numberCredits open() addStudent(StudentInfo) major location tenureStatus ScheduleAlgorithm 1 0..* 1..* 4 3..10 0..4 ?

46 Diagrams in UML – Inheritance
Inheritance is a relationship between a superclass and its subclasses Common attributes, operations, and/or relationships are shown at the highest applicable level in the hierarchy ScheduleAlgorithm RegistrationForm RegistrationManager Course addStudent(Course, StudentInfo) name numberCredits open() addStudent(StudentInfo) major location tenureStatus RegistrationUser name Student Professor CourseOffering

47 Diagrams in UML – State Transition Diagram
The life history of a given class The events that cause a transition from one state to another The actions that result from a state change Add Student / Set count = 0 Add student[ count < 10 ] [ count = 10 ] Cancel Initialization Open do: Initialize course do: Finalize course do: Notify registered students entry: Register student exit: Increment count Canceled Closed What class is this for?

48 Diagrams in UML – Statechart Diagram
shows a state machine, consisting of states, transitions, events and activities Add student[ Count < 10 ] Add student / Set count = 0 Initialization Open [ Count = 10 ] ^Course Report.Create report State charts allow hierarchic modeling of states and transition between such hierarchic states. This allows for the encapsulation of behaviors. They also provide an elegant expression of multiple, parallel behaviors. State charts remain humanly tractable even for complex systems. State transition diagrams lack these devices and quickly become incomprehensible, even for specifications of modest complexity. Cancel course Cancelled Closed Cancel course What’s the difference between a state transition diagram and a StateChart?

49 Diagrams in UML – Activity Diagrams
A special kind of statechart diagram that shows the flow from activity to activity. Not directly supported in Rational Rose 98 Body Prepare for speech Swimlanes a mechanism to group and organize activity states Decompress Gesture Synch Mouth Stream Audio Cleanup

50 Diagrams in UML – Activity Diagrams
How do we represent these if not supported by UML, or Rational Rose? Place a state at each synchronization bar! Prepare for speech Decompress This is the result (Can you figure this out?) Synch Mouth Stream Audio Gesture Gesture Prepare for speech Decompress Synch Mouth Stream Audio Cleanup Sync 1 Sync 2 sync3 Sync 4 Synchronization Cleanup

51 Diagrams in UML – Component Diagram
shows the organizations and dependencies among a set of components. Register.exe Billing.exe Billing System Registrar.exe People.dll User Course.dll Course Courses.dll People.dll Professor Student Course Course Offering

52 Diagrams in UML – Deployment Diagram
The deployment diagram shows the configuration of run-time processing elements and the software processes living on them. The deployment diagram visualizes the distribution of components across the enterprise. Registration Database Library Dorm Main Building

53 Extensibility of UML Stereotypes can be used to extend the UML notational elements Stereotypes may be used to classify and extend associations, inheritance relationships, classes, and components Examples: Class stereotypes: boundary, control, entity, utility, exception Inheritance stereotypes: uses and extends Component stereotypes: subsystem Stereotypes — extends vocabulary. Tagged values — extends properties of UML building blocks. Constraints — extend the semantics of UML building blocks.

54 Using UML Concepts in a Nutshell
Display the boundary of a system & its major functions using use cases and actors Illustrate use case realizations with interaction diagrams Represent a static structure of a system using class diagrams Model the behavior of objects with state transition diagrams Reveal the physical implementation architecture with component & deployment diagrams Extend your functionality with stereotypes

55 Process for Using UML - But No Silver Bullet
main reason for using the iterative life cycle: Not all the needed information up front Changes throughout the development period expect To face some persistent, recurring risks To discover new risks along the way To do some rework; to throw away some lines of code To change requirements along the way

56 Summary Background What is UML for?
for visualizing, specifying, constructing, and documenting models Building blocks of UML Things, Relationships (4 kinds) and Diagrams (7 different kinds) Process for Using UML Use case-driven, Architecture-centric, & Iterative and incremental

57 Points to Ponder How much unification does UML do?
Consider the Object Model Notation on the inside cover on the front and back of the textbook "Object Oriented Modeling and Design" by Rumbaugh, et.al. List the OMT items that do not exist in UML List the UML items that do not exist in OMT For those items of OMT for which UML equivalents exist, map the notation to UML. Where would you want to use stereotypes? Model the “Business Process” on page 6 in UML. Map the four (4) phases of the RUP to the traditional software lifecycle. If an object refers to a concept, can an object refer to a concept of an concept? Consider some examples. What would be the essential differences between a property and an attribute? Consider some examples. What is the syntax and semantics of a class diagram? In Component-Based Software Engineering (CBSE), components are the units, or building blocks, of a (distributed) software system. What kind of building blocks of UML can be components for CBSE?

58 Module 2: Introduction to UML - Appendix

59 Architecture & Views UML is for visualizing, specifying, constructing, and documenting with emphasis on system architectures (things in the system and relationships among the things) from five different views Architecture - set of significant decisions regarding: Organization of a software system. Selection of structural elements & interfaces from which a system is composed. Behavior or collaboration of elements. Composition of structural and behavioral elements. Architectural style guiding the system. Design View Implementation View vocabulary functionality system assembly configuration mgmt. Use Case View behavior Process View Deployment View system topology distribution delivery installation performance scalability throughput

60 Views Use Case View Design View
Use Case Analysis is a technique to capture business process from user’s perspective. Encompasses the behavior as seen by users, analysts and testers. Specifies forces that shape the architecture. Static aspects captured in use case diagrams. Dynamic aspects captured in interaction diagrams, statechart diagrams, and activity diagrams. Design View Encompasses classes, interfaces, and collaborations that define the vocabulary of a system. Supports functional requirements of the system. Static aspects captured in class diagrams and object diagrams. Dynamic aspects captured in interaction, statechart, and activity diagrams.

61 Views Process View Implementation View Deployment View
Encompasses the threads and processes defining concurrency and synchronization. Addresses performance, scalability, and throughput. Static and dynamic aspects captured as in design view; emphasis on active classes. Implementation View Encompasses components and files used to assemble and release a physical system. Addresses configuration management. Static aspects captured in component diagrams. Dynamic aspects captured in interaction, statechart, & activity diagrams. Deployment View Encompasses the nodes that form the system hardware topology. Addresses distribution, delivery, and installation. Static aspects captured in deployment diagrams. Dynamic aspects captured in interaction, statechart, & activity diagrams.

62 Rules of UML Well formed models — semantically self-consistent and in harmony with all its related models. Semantic rules for: Names — what you can call things. Scope — context that gives meaning to a name. Visibility — how names can be seen and used. Integrity — how things properly and consistently relate to one another. Execution — what it means to run or simulate a dynamic model. Avoid models that are Elided — certain elements are hidden for simplicity. Incomplete — certain elements may be missing. Inconsistent — no guarantee of integrity.

63 The Rational Unified Process (RUP)
Process for Using UML How do we use UML as a notation to construct a good model? Use case driven — use cases are primary artifact for defining behavior of the system. Architecture-centric — the system’s architecture is primary artifact for conceptualizing, constructing, managing, and evolving the system. Iterative and incremental — managing streams of executable releases with increasing parts of the architecture included. A well-defined process will guide you in deciding what artifacts to produce, what activities and what workers to use to create them and manage them, and how to use those artifacts to measure and control the project as a whole. The Rational Unified Process (RUP)

64 Process for Using UML - Iterative Life Cycle
It is planned, managed and predictable …almost It accommodates changes to requirements with less disruption It is based on evolving executable prototypes, not documentation It involves the user/customer throughout the process It is risk driven Primary phases Inception — seed idea is brought up to point of being a viable project. Elaboration — product vision and architecture are defined. ( Construction — brought from architectural baseline to point of deployment into user community. Transition — turned over to the user community.

65 Process for Using UML - Iterative Approach
Three Important Features Continuous integration - Not done in one lump near the delivery date Frequent, executable releases - Some internal; some delivered Attack risks through demonstrable progress - Progress measured in products, not documentation or engineering estimates Resulting Benefits Releases are a forcing function that drives the development team to closure at regular intervals - Cannot have the “90% done with 90% remaining” phenomenon Can incorporate problems/issues/changes into future iterations rather than disrupting ongoing production The project’s supporting elements (testers, writers, toolsmiths, QA, etc.) can better schedule their work

66 Process for Using UML - Risk Reduction Drives Iterations
Define scenarios to address highest risks Plan Iteration N Cost Schedule Initial Project Risks Initial Project Scope Develop Iteration N Collect cost and quality metrics Iteration N Assess Iteration N Revise Overall Project Plan Cost Schedule Scope/Content Risks Eliminated Revise Project Risks Reprioritize

67 Process for Using UML - Use Cases Drive the Iteration Process
Inception Elaboration Construction Transition Iteration 1 Iteration 2 Iteration 3 Each iteration is defined in terms of the scenarios it implements “Mini-Waterfall” Process Results of previous iterations Up-to-date risk assessment Controlled libraries of models, code, and tests Selected scenarios Iteration Planning Reqs Capture Analysis & Design Implementation Test Release description Updated risk assessment Controlled libraries Prepare Release

68 Points to Ponder Are Sequence and Collaboration Diagrams Isomorphic?

69 Use Case Diagrams Use case Interaction Diagrams Behavioral Diagrams
Statechart Activity Interaction Diagrams Sequence; Communication Interaction Overview Timing

70 Use Cases

71 Use Case : Definition A sequence of actions a system performs that yields observable results of value to a particular Actor. Describes a piece of the functional requirement of the system as seen by the customer “A use case is a specific way of using the system by performing some part of the functionality. Each use case constitutes a complete course of events initiated by an actor, and it specifies the interaction that takes place between an actor and the system…...

72 UML Notation for Uses Cases
Apply for membership Open An Account RegisterForAclass

73 Purpose of Use Cases Capture the requirements of a system in terms of the Customer Language Derive System Analysis Derive System Design Derive System Implementation Derive System Test

74 Actor Is someone or something outside the system that interacts with the system, either by giving or receiving information or both. Types of Actors: different human users roles interact with our system other software systems/applications hardware systems/devices

75 Actors An actor is someone or some thing that must interact with the system under development Cashier Police Officer Student Billing System 14

76 Actors Office Personnel Foreman Legacy Warehouse Database Worker
Truck Driver

77 Use Case Diagram Maintain Instructor Information Registrar
Actor Relationships Use Case Maintain Instructor Information Registrar Create Course Catalogue Maintain Student Information

78 Actor – Use Case Relationships
An actor is a user role, a kind of stereotype. The actor is symbolized with a “stick man” figure with the name of the actor below the figure. A use case is shown as an ellipse, with a name inside identifying the use case. When an actor is involved in a use case, a line is drawn from the actor to the use case. We say that the actor communicates with the use case. Who is initiating the communication can be indicated by an arrowhead. actor use case actor use case The actor initiate the communication. actor use case The use case initiate the communication. Both actor and use case can initiate the communication.

79 Use Case Example RelocateItems CleanInventory CancelOrder ProcessOrder

80 Use case Diagram Show a set of use cases and actors and the relationships between them. Represent the static use case view of a system. Used to represent the requirements of a system. Contain: Use cases Actors Use Case Relationships System Boundary

81 Use Case Notation System Boundary Use Case Actor A B C
A use case is a sequence of actions a system performs that yields an observable result of value to a particular actor. Use Case A Actor B C An actor is someone or something outside the system that interacts with the system. Jacobson ‘94

82 Use Case Diagram

83 Example: Online HR System

84 Use-Case Diagram Example
register as student adm register for course student register for exam instructor works with course lab make/edit course lecturer System Boundary

85 Use Case – Exercise Indian Railways provides for advance reservation on all long-distance travel. The passenger seeking reservation of berth or seats should purchase the tickets from Railway Reservation Offices or Authorised Travel Agency only. To make an advance booking, the passenger is expected to fill in a prescribed application form and submit it to the reservation counter with the appropriate amount. Advanced Reservations are made up to 60 days in advance for all trains, for all classes exclusive of the day of departure of trains. An individual can book only up to six passengers on one requisition form provided all passengers are for the same destination and for the same train. Use cases are narrative descriptions of business processes. A use case describes from start to finish, a sequence of events, actions, and transactions required to produce or complete something of value to an actor. They are stories or cases of using a system. Use cases are not exactly requirements or functional specifications, but they illustrate and imply requirements.

86 Use Case - Exercise (contd.)
Indian Railways wishes to develop a ticketing and reservation system. This must support advance booking of tickets, cancellation of tickets and change of class of a ticket. All these are handled by a Reservation Clerk. The system will also have a web-interface where users can register themselves and purchase tickets online. They can pay either by using their online banking account or by credit card or by VPP. Reservations made over the internet can only be cancelled across the counter. The system will also have a querying facility that allows users to check train time-tables, fares and availability of tickets.

87 Use Case - Example (contd.)
Use Cases: Make Reservation Cancel Reservation Modify Class Print Ticket Query Timetable Check Fare Use cases are narrative descriptions of business processes. A use case describes from start to finish, a sequence of events, actions, and transactions required to produce or complete something of value to an actor. They are stories or cases of using a system. Use cases are not exactly requirements or functional specifications, but they illustrate and imply requirements. Register as Member

88 Use Case Relationships

89 Four Use Case Relationships
Uses Includes Generalizes Extends

90 Use-Case Diagram

91 Online HR System: Use Case Relationships

92 The <<extends>> Relationship
<<extends>> relationships represent exceptional or 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 <<extends>> relationship is to the extended use case Passenger BookFlightByPhone BookFlightByOperator <<extends>>

93 The <<includes>> Relationship
Customer <<includes>> relationship represents a common behavior among several use cases. This behavior is factored for reuse and for reducing the complexity of other use cases. PurchaseAutomobile ApplyForLoan <<includes>> CheckCredit <<includes>>

94 The Generalization Relationship
Passenger AuthenticateUser AutenticateUsingPassword

95 Finding Use Cases: Useful Questions
What are the tasks of each actor? Will the actor create, store, change, remove, or read information in the system? What use case will create, store, change, remove, or read information in the system? Will the actor need to inform the system about sudden, external changes?

96 Finding Use Cases: Useful Questions
Does the actor need to be informed about certain occurrences in the system? Does the system supply the business with the correct behavior? What use cases will support and maintain the system? Can all functional requirements be performed by the use cases?

97 Scenarios “A narrative description of what people do and experience as they try to make use of computer systems and applications” [M. Carrol, Scenario-based Design, Wiley, 1995] A concrete, focused, informal description of a single feature of the system used by a single actor. Scenarios can have many different uses during the software lifecycle

98 What are Scenarios ? A scenario is an instance of a use case
It is one flow through a use case Each use case will have a web of scenarios Primary scenarios (happy day scenarios) Normal flow - the way the system should work Secondary scenarios Exceptions to the primary scenario

99 Use Case Flow of Events

100 How do we find scenarios?
Don’t expect the client to be verbal if the system does not exist (greenfield engineering) Don’t wait for information even if the system exists Engage in a dialectic approach (evolutionary, incremental) You help the client to formulate the requirements The client helps you to understand the requirements The requirements evolve while the scenarios are being developed

101 Heuristics for finding Scenarios
Ask yourself or the client the following questions: What are the primary tasks that the system needs to perform? What data will the actor create, store, change, remove or add in the system? What external changes does the system need to know about? What changes or events will the actor of the system need to be informed about? Insist on task observation if the system already exists (interface engineering or reengineering) Ask to speak to the end user, not just to the software contractor Expect resistance and try to overcome it

102 Exercise: Use Case Diagram in UML
The SMU wants to computerize its registration system The Registrar sets up the curriculum for a semester Students select 3 core courses and 2 electives Once a student registers for a semester, the billing system is notified so the student may be billed for the semester Students may use the system to add/drop courses for a period of time after registration Professors use the system to set their preferred course offerings and receive their course offering rosters after students register Users of the registration system are assigned passwords which are used at logon validation

103 Diagrams in UML – Actors in Use Case Diagram
An actor is someone or some thing that must interact with the system under development The SMU wants to computerize its registration system The Registrar sets up the curriculum for a semester Students select 3 core courses and 2 electives Once a student registers for a semester, the billing system is notified so the student may be billed for the semester Students may use the system to add/drop courses for a period of time after registration Professors use the system to set their preferred course offerings and receive their course offering rosters after students register Users of the registration system are assigned passwords which are used at logon validation Registrar Student Billing System Professor

104 Diagrams in UML – Use Cases in Use Case Diagram
A use case is a sequence of interactions between an actor and the system Maintain Curriculum The SMU wants to computerize its registration system The Registrar sets up the curriculum for a semester Students select 3 core courses and 2 electives Once a student registers for a semester, the billing system is notified so the student may be billed for the semester Students may use the system to add/drop courses for a period of time after registration Professors use the system to set their preferred course offerings and receive their course offering rosters after students register Users of the registration system are assigned passwords which are used at logon validation Register for Courses Registrar Student Billing System Request Course Roster Set Course Offerings Professor

105 Diagrams in UML – Use Case Diagram
Use case diagrams depict the relationships between actors and use cases SMU Registration System system boundary Maintain Curriculum Registrar Register for Courses Billing System Student Manage Seminar Request Course Roster Anything wrong? Set Course Offerings Professor

106 Diagrams in UML - Uses and Extends in Use Case Diagram
A uses relationship shows behavior common to one or more use cases An extends relationship shows optional/exceptional behavior <<uses>> <<extends>> Register for courses Register for Distance Learning courses <<uses>> Logon validation <<uses>> Maintain curriculum Create course <<uses>> Maintain Schedule

107 Diagrams in UML – Flow of Events for each use case: Typical contents:
Diagrams in UML – Flow of Events for each use case: Typical contents: How the use case starts and ends Normal flow of events (focus on the normal first!) Alternate/Exceptional flow of events Flow of Events for Creating a Course Registrar Create Course This use case begins after the Registrar logs onto the Registration System with a valid password. The registrar fills in the course form with the appropriate semester and course related info. The Registrar requests the system to process the course form. The system creates a new course, and this use case ends

108 Use Cases When to Use Use Cases
Fowler’s View: do use cases first before object modeling Capture the simple, normal use-case first For every step ask “What could go wrong?” and how it might work out differently Plot all variations as extensions of the given use case Another view: do object modeling first, then use cases Another: iterate model - use case - model - use case ... What did we do? Scenarios describe a single path, or a particular sequence E.g., Use Case: Order Goods Scenario 1: all goes well Scenario 2: insufficient funds Scenario 3: out of stock System test cases: Generate a test script for each scenario (flow of events). Obtain initial state from preconditions. Test success against post conditions.

109 <<extend>>
Organizing Use Cases Generalization, Extend, Include/Use, packages does a bit more or deals with a special situation extension point extension Place order Extension points: set priority <<extend>> (set priority) Place rush order extension use case <<include>> inclusion use case Check password inclusion Validate user Track order generalization <<include>> child use case common to multiple use cases; Often no actor may be associated with a ‘used’ use case Retinal scan base use case Track Order - Obtain and verify the order number; For each part in the order, query its status, then report back to the user. Place Order - Collect the user’s order items. (set priority). Submit the order for processing. UML 1.3: Replaces <<uses>> relationship with Generalization and <<include>> dependency (

110 A Use Case Template (http://www.bredemeyer.com/pdf_files/use_case.pdf)
Identifier: e.g., “Withdraw money”; ref # = wm3; mod history = … Actors List of actors involved in use case Brief description Goal: E.g., “This use case lets a bank account owner withdraw money from an ATM machine”; Source: Bank doc 2.3 Preconditions What should be true before the use case can start. Postconditions What should hold after the use case successfully completes. Basic flow of events The happy/sunny day flow. The most common successful case. Alt. flow of events /subflows Difference for the specific subflow Exception flows Subflows may be divided into 1) normal, 2) successful alternate actions, and 3) exception/error flows. Non-Functional (optional) List of NFRs that the use case must meet Issues List of issues that remain to be resolved

111 A Use Case Template (http://www.bredemeyer.com/pdf_files/use_case.pdf)
Use Case (id, ref#, mod history) 2. Reparing_Cellular_Network History created 1/5/98 Derek Coleman, modified 5/5/98 Description (goal, source) Operator rectifies a report by changing parameters of a cell Actors Operator (primary, Cellular network, Field maintenance engineer) Assumptions (successful use case termination condition) Changes to network are always successful when applied to a network Steps Operator notified of network problem Operator starts repair session REPEAT 3.1 Operator runs network diagnosis application 3.2 Operator identifies cells to be changes and their new parameter values 3.3 IN PARALLEL 3.3.1 Maintenance engineer tests network cells || 3.3.2 Maintenance engineer sends fault reports UNTIL no more reports of problem 4. Operator closes repair session Variations (optional) #1. System may detect fault and notify operator or Field maintenance engineer may report fault to Operator Non-Functional (optional) Performance Mean: time to repair network fault must be less than 3 hours Issues (that remain to be resolved) What are the modes of communication between field maintenance engineer and operator Use Case Extension Repair_may_fail extends 2. Reparing_Cellular_Network Description Deals with assumption that network changes can never fail Steps #3.3. if the changes to network fail then the network is rolled back to its previous state Issues How are failures detected? Are roll backs automatic or is Operator intervention required?

112 Class Diagrams & Object Diagrams

113 Essentials of UML Class Diagrams
The main symbols shown on class diagrams are: Classes represent the types of data themselves Associations represent linkages between instances of classes Attributes are simple data found in classes and their instances Operations represent the functions performed by the classes and their instances Generalizations group classes into inheritance hierarchies

114 Classes A class is simply represented as a box with the name of the class inside The diagram may also show the attributes and operations The complete signature of an operation is: operationName(parameterName: parameterType …): returnType

115 Associations and Multiplicity
An association is used to show how two classes are related to each other Symbols indicating multiplicity are shown at each end of the association

116 Labelling associations
Each association can be labelled, to make explicit the nature of the association

117 Analyzing and validating associations
One-to-one For each company, there is exactly one board of directors A board is the board of only one company A company must always have a board A board must always be of some company

118 Analyzing and validating associations
Many-to-many A secretary can work for many managers A manager can have many secretaries Secretaries can work in pools Managers can have a group of secretaries Some managers might have zero secretaries. Is it possible for a secretary to have, perhaps temporarily, zero managers?

119 Analyzing and validating associations
Avoid unnecessary one-to-one associations Avoid this do this

120 A more complex example A booking is always for exactly one passenger
no booking with zero passengers a booking could never involve more than one passenger. A Passenger can have any number of Bookings a passenger could have no bookings at all a passenger could have more than one booking

121 Association classes Sometimes, an attribute that concerns two associated classes cannot be placed in either of the classes The following are equivalent Registration grade Student CourseSection * Registration grade Student CourseSection *

122 Reflexive associations
It is possible for an association to connect a class to itself successor * Course isMutuallyExclusiveWith * * * prerequisite

123 Directionality in associations
Associations are by default bi-directional It is possible to limit the direction of an association by adding an arrow at one end * * Day Note

124 Generalization Specializing a superclass into two or more subclasses
The discriminator is a label that describes the criteria used in the specialization

125 Avoiding unnecessary generalizations
Inappropriate hierarchy of classes, which should be instances Recording * RecordingCategory Improved class diagram, with its corresponding instance diagram hasCategory * title description subcategory artist :RecordingCategory :RecordingCategory video audio subcategory subcategory subcategory subcategory subcategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory music video jazz classical blues rock :Recording :Recording 9th Symphony Let it be Beethoven The Beatles

126 Handling multiple discriminators
Creating higher-level generalization

127 Handling multiple discriminators
Using multiple inheritance Animal habitat typeOfFood AquaticAnimal LandAnimal Carnivore Herbivore AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore

128 Avoiding having instances change class
An instance should never need to change class

129 Object Diagrams A link is an instance of an association
In the same way that we say an object is an instance of a class Pat:Employee Wayne:Employee OOCorp:Company OOCorp's Board: Ali:Employee Carla:Employee UML inc:Company UML inc's Board Terry:Employee

130 Associations versus generalizations in object diagrams
Associations describe the relationships that will exist between instances at run time. When you show an object diagram generated from a class diagram, there will be instances of both classes joined by an association Generalizations describe relationships between classes in class diagrams. They do not appear in object diagrams at all. An instance of any class should also be considered to be an instance of each of that class’s superclasses

131 More Advanced Features: Aggregation
Aggregations are special associations that represent ‘part-whole’ relationships. The ‘whole’ side is often called the assembly or the aggregate This symbol is a shorthand notation association named isPartOf Vehicle * * * * VehiclePart * * * * * * Country Region

132 When to use an aggregation
As a general rule, you can mark an association as an aggregation if the following are true: You can state that the parts ‘are part of’ the aggregate or the aggregate ‘is composed of’ the parts When something owns or controls the aggregate, then they also own or control the parts

133 Composition A composition is a strong kind of aggregation
if the aggregate is destroyed, then the parts are destroyed as well Two alternatives for addresses * * * * * Building Room

134 Aggregation hierarchy
Vehicle * * Chassis BodyPanel Door * Frame Engine Transmission Wheel

135 Propagation A mechanism where an operation in an aggregate is implemented by having the aggregate perform that operation on its parts At the same time, properties of the parts are often propagated back to the aggregate Propagation is to aggregation as inheritance is to generalization. The major difference is: inheritance is an implicit mechanism propagation has to be programmed when required

136 Interfaces An interface describes a portion of the visible behaviour of a set of objects. An interface is similar to a class, except it lacks instance variables and implemented methods «interface» Person Machine Person Machine Cashier withdraw Cashier Cashier deposit Employee ATM Employee ATM

137 Notes and descriptive text
Descriptive text and other diagrams Embed your diagrams in a larger document Text can explain aspects of the system using any notation you like Highlight and expand on important features, and give rationale Notes: A note is a small block of text embedded in a UML diagram It acts like a comment in a programming language

138 Object Constraint Language (OCL)
OCL is a specification language designed to formally specify constraints in software modules An OCL expression simply specifies a logical fact (a constraint) about the system that must remain true A constraint cannot have any side-effects it cannot compute a non-Boolean result nor modify any data. OCL statements in class diagrams can specify what the values of attributes and associations must be

139 OCL statements OCL statements can be built from:
References to role names, association names, attributes and the results of operations The logical values true and false Logical operators such as and, or, =, >, < or <> (not equals) String values such as: ‘a string’ Integers and real numbers Arithmetic operations *, /, +, -

140 An example: constraints on Polygons
{edge->forAll(e1,e2 | e1 <> e2 implies e1.startPoint <> e2.startpoint a LinearShape is any shape and e1.endPoint <> e2.endpoint)} that can be constructed of line {ordered} edge LinearShape LineSegment segments (in contrast with 1..* shapes that contain curves). startPoint: Point endPoint: Point length : int Path Line Polygon {startPoint <> endPoint} length {edge->size=1} {edge->first.startPoint = edge->last.endPoint} {length = edge.length->sum} RegularPolygon {edge->forAll(e1,e2 | e1.length = e2.length)}

141 Detailed Example: A Class Diagram for Genealogy
2 child Person name placeOfBirth dateOfBirth placeOfDeath dateOfDeath placeOfMarriage dateOfMarraige dateOfDivorce * parent {parent->forAll(p1,p2: p1 <> p2 implies p1.sex <> p2.sex)} sex Problems A person must have two parents Marriages not properly accounted for

142 Genealogy example: Possible solutions
Person name placeOfBirth dateOfBirth placeOfDeath dateOfDeath Union placeOfMarriage dateOfMarriage dateOfDivorce parents 0..1 child * malePartner femalePartner Woman Man Person name placeOfBirth dateOfBirth placeOfDeath dateOfDeath Union placeOfMarriage dateOfMarriage dateOfDivorce parents 0..1 child * partner 0..2 sex {partner->forAll(p1,p2 | p1 <> p2 implies p1.sex <> p2.sex)}

143 The Process of Developing Class Diagrams
You can create UML models at different stages and with different purposes and levels of details Exploratory domain model: Developed in domain analysis to learn about the domain System domain model: Models aspects of the domain represented by the system System model: Includes also classes used to build the user interface and system architecture

144 System domain model vs System model
The system domain model omits many classes that are needed to build a complete system Can contain less than half the classes of the system. Should be developed to be used independently of particular sets of user interface classes architectural classes The complete system model includes The system domain model User interface classes Architectural classes Utility classes

145 Suggested sequence of activities
Identify a first set of candidate classes Add associations and attributes Find generalizations List the main responsibilities of each class Decide on specific operations Iterate over the entire process until the model is satisfactory Add or delete classes, associations, attributes, generalizations, responsibilities or operations Identify interfaces Apply design patterns Don’t be too disorganized. Don’t be too rigid either.

146 Identifying classes When developing a domain model you tend to discover classes When you work on the user interface or the system architecture, you tend to invent classes Needed to solve a particular design problem (Inventing may also occur when creating a domain model) Reuse should always be a concern Frameworks System extensions Similar systems

147 A simple technique for discovering domain classes
Look at a source material such as a description of requirements Extract the nouns and noun phrases Eliminate nouns that: are redundant represent instances are vague or highly general not needed in the application Pay attention to classes in a domain model that represent types of users or other actors

148 Exercise: Airline Reservation System
Ootumlia Airlines runs sightseeing flights from Java Valley, the capital of Ootumlia. The reservation system keeps track of passengers who will be flying in specific seats on various flights, as well as people who will form the crew. For the creaw, the system needs to track what everyone does, and who supervises whom. Ootumilia Airlines runs several daily numbered flights on a regular schedule. Ootumlia Airline expects to expand in the future, therefore the system needs to be flexible; in particular, it will be adding a frequent-flier plan. List the nouns and noun phrases that might end up being classes in a system domain model. For those nouns that should not become classes, explain why not

149 Identifying associations and attributes
Start with classes you think are most central and important Decide on the clear and obvious data it must contain and its relationships to other classes. Work outwards towards the classes that are less important. Avoid adding many associations and attributes to a class A system is simpler if it manipulates less information

150 Tips about identifying and specifying valid associations
An association should exist if a class possesses controls is connected to is related to is a part of has as parts is a member of, or has as members some other class in your model Specify the multiplicity at both ends Label it clearly.

151 Actions versus associations
A common mistake is to represent actions as if they were associations LibraryPatron * * * * * * LibraryPatron Loan borrowedDate dueDate returnedDate borrow return * * * * CollectionItem CollectionItem Bad, due to the use of associations Better: The borrow operation creates a Loan, and the return operation sets the returnedDate attribute that are actions

152 Identifying attributes
Look for information that must be maintained about each class Several nouns rejected as classes, may now become attributes An attribute should generally contain a simple value E.g. string, number

153 Tips about identifying and specifying valid attributes
It is not good to have many duplicate attributes If a subset of a class’s attributes form a coherent group, then create a distinct class containing these attributes

154 Exercise: For the Airline Reservation System, add an initial set of attributes and associations to the classes you identified. Add and delete classes as necessary. * supervisor RegularFlight time flightNumber Passenger SpecificFlight date name employeeNumber Employee jobFunction Booking seatNumber number

155 Identifying generalizations and interfaces
There are two ways to identify generalizations: bottom-up Group together similar classes creating a new superclass top-down Look for more general classes first, specialize them if needed Create an interface, instead of a superclass if The classes are very dissimilar except for having a few operations in common One or more of the classes already have their own superclasses Different implementations of the same class might be available

156 Exercise: For Airline Reservation System, add any obvious generalizations, making whatever other changes become necessary. * supervisor RegularFlight time flightNumber PassengerRole SpecificFlight date Person name idNumber 0..2 EmployeeRole jobFunction Booking seatNumber PersonRole

157 Allocating responsibilities to classes
A responsibility is something that the system is required to do. Each functional requirement must be attributed to one of the classes All the responsibilities of a given class should be clearly related. If a class has too many responsibilities, consider splitting it into distinct classes If a class has no responsibilities attached to it, then it is probably useless When a responsibility cannot be attributed to any of the existing classes, then a new class should be created To determine responsibilities Perform use case analysis Look for verbs and nouns describing actions in the system description

158 Categories of responsibilities
Setting and getting the values of attributes Creating and initializing new instances Loading to and saving from persistent storage Destroying instances Adding and deleting links of associations Copying, converting, transforming, transmitting or outputting Computing numerical results Navigating and searching Other specialized work

159 Exercise: For Airline Reservation System, allocate the responsibilities to a class and discuss your reasoning for allocation. Finally update the class diagram as necessary. Creating a new regular flight Searching for a flight Modifying attributes of a flight Creating a specific flight Booking a passenger Canceling a booking * supervisor RegularFlight time flightNumber PassengerRole SpecificFlight date Person name idNumber 0..2 EmployeeRole jobFunction Booking seatNumber PersonRole Airline

160 Prototyping a class diagram on paper-CRC
CRC – Class-Responsibility-Collaboration As you identify classes, you write their names on small cards As you identify attributes and responsibilities, you list them on the cards If you cannot fit all the responsibilities on one card: this suggests you should split the class into two related classes. Move the cards around on a whiteboard to arrange them into a class diagram. Draw lines among the cards to represent associations and generalizations.

161 Identifying operations
Operations are needed to realize the responsibilities of each class There may be several operations per responsibility The main operations that implement a responsibility are normally declared public Other methods that collaborate to perform the responsibility must be as private as possible

162 An example (class collaboration)
EmployeeRole + getName [e2] crewMember * * * * * * * Booking Airplane SpecificFlight * 0..1 * * * * * * addLinkToSpecificFlight [a2, d3] Booking [c2] + specifyAirplane [a1] deleteLinkToSpecificFlight [d2] + createFlightLog [b1] * + changeAirplane [d1] + findCrewMember [e1] 0..1 FlightLog PassengerRole addLinkToBooking [c3] FlightLog [b2] + makeBooking [c1] addLinkToBooking [c4]

163 Class collaboration ‘a’
Making a bi-directional link between two existing objects; e.g. adding a link between an instance of SpecificFlight and an instance of Airplane. 1. (public) The instance of SpecificFlight makes a one-directional link to the instance of Airplane then calls operation 2. 2. (non-public) The instance of Airplane makes a one-directional link back to the instance of SpecificFlight

164 Class collaboration ‘b’
Creating an object and linking it to an existing object e.g. creating a FlightLog, and linking it to a SpecificFlight. 1. (public) The instance of SpecificFlight calls the constructor of FlightLog (operation 2) then makes a one-directional link to the new instance of FlightLog. 2. (non-public) Class FlightLog’s constructor makes a one-directional link back to the instance of SpecificFlight.

165 Class collaboration ‘c’
Creating an association class, given two existing objects e.g. creating an instance of Booking, which will link a SpecificFlight to a PassengerRole. 1. (public) The instance of PassengerRole calls the constructor of Booking (operation 2). 2. (non-public) Class Booking’s constructor, among its other actions makes a one-directional link back to the instance of PassengerRole makes a one-directional link to the instance of SpecificFlight calls operations 3 and 4. 3. (non-public) The instance of SpecificFlight makes a one-directional link to the instance of Booking. 4. (non-public) The instance of PassengerRole

166 Class collaboration ‘d’
Changing the destination of a link e.g. changing the Airplane of to a SpecificFlight, from airplane1 to airplane2  1. (public) The instance of SpecificFlight deletes the link to airplane1 makes a one-directional link to airplane2 calls operation 2 then calls operation 3. 2. (non-public) airplane1 deletes its one-directional link to the instance of SpecificFlight. 3. (non-public) airplane2 makes a one-directional link to the instance of SpecificFlight.

167 Class collaboration ‘e’
Searching for an associated instance e.g. searching for a crew member associated with a SpecificFlight that has a certain name. 1. (public) The instance of SpecificFlight creates an Iterator over all the crewMember links of the SpecificFlight\ for each of them call operation 2, until it finds a match. 2. (may be public) The instance of EmployeeRole returns its name.

168 Implementing Class Diagrams in Java
Attributes are implemented as instance variables Generalizations are implemented using extends Interfaces are implemented using implements Associations are normally implemented using instance variables Divide each two-way association into two one-way associations so each associated class has an instance variable. For a one-way association where the multiplicity at the other end is ‘one’ or ‘optional’ declare a variable of that class (a reference) For a one-way association where the multiplicity at the other end is ‘many’: use a collection class implementing List, such as Vector

169 Example: SpecificFlight
class SpecificFlight { private Calendar date; private RegularFlight regularFlight; private TerminalOfAirport destination; private Airplane airplane; private FlightLog flightLog; private ArrayList crewMembers; // of EmployeeRole private ArrayList bookings ... }

170 Example: SpecificFlight
// Constructor that should only be called from // addSpecificFlight SpecificFlight( Calendar aDate, RegularFlight aRegularFlight) { date = aDate; regularFlight = aRegularFlight; }

171 Example: RegularFlight
class RegularFlight { private ArrayList specificFlights; ... // Method that has primary // responsibility public void addSpecificFlight( Calendar aDate) SpecificFlight newSpecificFlight; newSpecificFlight = new SpecificFlight(aDate, this); specificFlights.add(newSpecificFlight); }

172 Exercise: A binary tree either is empty (no nodes), or has a root node, a left tree, and a right binary. Is the following a good model of a binary tree. If not, present a correct UML model.

173


Download ppt "Module 2: Introduction to UML"

Similar presentations


Ads by Google