Module 2 Introduction to UML Background q What

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

References n Documentation on UML is available from: ¨ UML 1. 5: http: //www. omg. org/technology/documents/formal/uml. htm ¨ UML n 2. 0: http: //www. uml. org/ Rational Rose is available from: ¨ n http: //www. rational. com Visual Modeling with Rational Rose and UML, Terry Quatrani, 1998. 2

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

What is UML? n. The Unified Modelling Language is a standard graphical language for modelling object oriented software ¨ At the end of the 1980 s and the beginning of 1990 s, 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. n They worked together at the Rational Software Corporation ¨ In 1995, another methodologist, Jacobson, joined the team n His work focused on use cases ¨ In 1997 the Object Management Group (OMG) started the process of UML standardization 4

What is UML? n 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. 5

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

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. 7

Unified Modeling Language (UML) n An effort by IBM (Rational) – OMG to standardize OOA&D notation n Combine the best of the best from n n ¨ 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 de facto industry standard 8

UML History n n n 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. ¨ ¨ ¨ n Rumbaugh joins Booch at Rational ’ 94 v 0. 8 draft Unified Method ’ 95 Jacobson joins Rational ’ 95 UML v 0. 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 - State. Chart) ¨ ¨ ¨ 9

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, … Places Order Sales Representative 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. 10

UML is also for … Specifying n n n 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 n n 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) 11

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

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

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

Structural Things in UML name 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 Window origin size attributes operations 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. IWindow name operations <<interface>> IWindow open() close() 15

Structural Things in UML 3. Collaboration Define an interaction among a web of objects. Define a society of roles and other elements. Provide cooperative behavior. Capture structural and behavioral dimensions. Chain of Responsibility Order management Order validation <<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 16

Structural Things in UML 5. Active Class Special class whose objects own one or more processes or threads. Can initiate control activity. Event Manager name attributes operations Thread time suspend() flush() Heavy border 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. Web. Server Variations on Structural Things: Actors, Signals, Utilities, Processes & Threads, Applications, Documents, etc. 17

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

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 19

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 20

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 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() } 21

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

Relationships in UML 1. Dependency 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. employer 0. . 1 Can be directed labels employee Can have multiplicity &*role names Aggregation a special kind of association. It represents a structural relationship between the whole and its parts. Represented by a diamond. 23

Relationships in UML 3. Generalization 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. . . 24

3 basic building blocks of UML - Relationships Student 1. Associations attends University 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 IGrade one element guarantees to carry out what is expected by the other element. (e. g, interfaces and classes/components; use cases and collaborations) harry: Student 4. Dependency <<instance. Of>> Student a change to one thing (independent) may affect the semantics of the other thing (dependent). (direction, label are optional) 25

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 ¨ ¨ ¨ Behavioral Diagrams Represent the dynamic aspects. ¨ Use case ¨ Sequence; Collaboration ¨ Statechart ¨ Activity Class; Object Component Deployment Composite Structure Package Behavioral Diagrams ¨ Interaction Diagrams Use case ¨ Sequence; Communication Statechart ¨ Activity ¨ Interaction Overvie 26 ¨ Timing ¨

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 systems behave internally • Component and deployment diagrams —show the various components of systems are arranged logically and physically 27

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 n ¨ ¨ ¨ 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 28

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

Diagrams in UML - Use Cases in Use Case Diagram n 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 – n 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 30

Diagrams in UML - Use Case Diagram n 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? 31

Diagrams in UML - Documenting Use Cases in Use Case Diagram n A flow of events is described in documents for each use case ¨ n n 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 ¨ 32

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 n n n 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 Set Course Offerings n n n Professor 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. 33

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 <<extends>> Register for Distance Learning courses <<uses>> Register for courses <<uses>> Logon validation Maintain curriculum 34

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? n 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. n Two types of interaction diagrams Sequence diagrams ¨ Collaboration diagrams ¨ 35

Diagrams in UML - Sequence Diagram n A sequence diagram displays object interactions arranged in a time sequence : Student registration form registration manager math 101 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? 36

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

Diagrams in UML - Class Diagrams n n 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 ¨ 38

Diagrams in UML - Classes n n 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 ¨ 39

Diagrams in UML - Classes: Naming & 3 Sections Schedule. Algorithm Registration. Form Registration. Manager Course Student Professor Course. Offering Which sequence/collaboration diagram are these from? 40

Diagrams in UML – Classes: Operations & Attributes Operations • • The behavior of a class is represented by its operations Operations may be found by examining interaction diagrams registration form registration manager 3: add course(Sue, math 01) Registration. Manager add. Course(Student, Course) 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 Each course offering has a number, location and time Course. Offering number location time 41

Diagrams in UML – Some Classes with Operations & Attributes Schedule. Algorithm Registration. Form Registration. Manager add. Student(Course, Student. Info) Course name number. Credits Student open() add. Student(Student. Info) name major Professor name tenure. Status Course. Offering location open() add. Student(Student. Info) 42

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” tenure. Status: true 43

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

Diagrams in UML – Relationships: Multiplicity and Navigation Schedule. Algorithm Registration. Form 0. . * 1 Registration. Manager add. Student(Course, Student. Info) Course 1 ? 0. . * Student name number. Credits open() add. Student(Student. Info) major 1 3. . 10 Professor tenure. Status 4 1 1. . * Course. Offering location 0. . 4 open() add. Student(Student. Info) 45

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 Schedule. Algorithm Registration. Form Registration. Manager add. Student(Course, Student. Info) Course name number. Credits Registration. User name Student open() add. Student(Student. Info) major Professor tenure. Status Course. Offering location open() add. Student(Student. Info) 46

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[ count < 10 ] Initialization Add Student / Set count = 0 do: Initialize course Open entry: Register student exit: Increment count Cancel [ count = 10 ] Canceled do: Notify registered students Cancel Closed do: Finalize course What class is this for? 47

Diagrams in UML – Statechart Diagram • shows a state machine, consisting of states, transitions, events and activities Add student[ Count < 10 ] Initialization Add student / Set count = 0 Open [ Count = 10 ] ^Course Report. Create report Cancel course Cancelled Closed Cancel course What’s the difference between a state transition diagram and a State. Chart? 48

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 49

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

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

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 Main Building Library Dorm 52

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. 53

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 54

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 55

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

Points to Ponder n 1. 2. 3. n n n n 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? 57

Module 2: Introduction to UML Appendix 58

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. vocabulary functionality Design View behavior performance scalability throughput Process View system assembly Implementation View configuration mgmt. Use Case View Deployment View system topology distribution delivery installation 59

Views Use Case View n n n 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 n n 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. 60

Views Process View n n n 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 n n 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 n n 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. 61

Rules of UML n Well formed models — semantically self-consistent and in harmony with all its related models. n 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. ¨ ¨ n 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. 62

Process for Using UML How do we use UML as a notation to construct a good model? n Use case driven — use cases are primary artifact for defining behavior of the system. n Architecture-centric n Iterative and incremental — the system’s architecture is primary artifact for conceptualizing, constructing, managing, and evolving the system. — managing streams of executable releases with increasing parts of the architecture included. The Rational Unified Process (RUP) 63

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. (http: //www. utdallas. edu/~chung/OOAD_SUMMER 04/HACS_vision_12. doc) ¨ Construction — brought from architectural baseline to point of deployment ¨ Transition — turned over to the user community. into user community. 64

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 65

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

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

Points to Ponder Are Sequence and Collaboration Diagrams Isomorphic? 68

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

Use Cases 70

Use Case : Definition n 71 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…. . .

UML Notation for Uses Cases Apply for membership Open An Account Register. For. Aclass 72

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

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

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

Actors Office Personnel Foreman Warehouse Worker 76 Truck Driver Legacy Database

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

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. use case actor Both actor and use can initiate the communication. use case actor The actor initiate the communication. use case actor The use case initiate the communication. 78

Use Case Example Relocate. Items Cancel. Order 79 Clean. Inventory Process. Order

Use case Diagram n n 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 80

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

Use Case Diagram 82

Example: Online HR System 83

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

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 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.

Use Case - Example (contd. ) Use Cases: Make Reservation Cancel Reservation Modify Class Print Ticket Query Timetable Check Fare Register as Member

Use Case Relationships 88

Four Use Case Relationships Uses n Includes n Generalizes n Extends n 89

Use-Case Diagram 90

Online HR System: Use Case Relationships 91

The <<extends>> Relationship n n Passenger n Book. Flight. By. Phone n <<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 <<extends>> Book. Flight. By. Operator 92

The <<includes>> Relationship n Customer Purchase. Automobile Apply. For. Loan <<includes>> Check. Credit 93 <<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.

The Generalization Relationship Passenger Authenticate. User Autenticate. Using. Password 94

Finding Use Cases: Useful Questions n n 95 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?

Finding Use Cases: Useful Questions n n 96 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?

Scenarios n “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] n A concrete, focused, informal description of a single feature of the system used by a single actor. n Scenarios can have many different uses during the software lifecycle 97

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

Use Case Flow of Events 99

How do we find scenarios? Don’t expect the client to be verbal if the system does not exist (greenfield engineering) n Don’t wait for information even if the system exists n Engage in a dialectic approach (evolutionary, incremental) n ¨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 100

Heuristics for finding Scenarios n 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? n 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 101

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

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

Diagrams in UML – Use Cases in Use Case Diagram n A use case is a sequence of interactions between an actor and the system The SMU wants to computerize its registration system n Maintain Curriculum The Registrar sets up the curriculum for a semester Register for Courses Registrar n Students select 3 core courses and 2 electives n Once a student registers for a semester, the billing system is notified so the student may be billed for the semester n n n Student Billing System Students may use the system to add/drop courses for a period of time after registration Request Course Roster 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 Professor Set Course Offerings 104

Diagrams in UML – Use Case Diagram n 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 Professor Set Course Offerings Anything wrong? 105

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 <<extends>> <<uses>> Register for courses Register for Distance Learning courses <<uses>> Logon validation <<uses>> Maintain curriculum <<uses>> Create course Maintain Schedule 106

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 n This use case begins after the Registrar logs onto the Registration System with a valid password. n The registrar fills in the course form with the appropriate semester and course related info. n The Registrar requests the system to process the course form. n The system creates a new course, and this use case ends 107

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

Organizing Use Cases • Generalization, Extend, Include/Use, packages does a bit more or deals with a special situation extension point extension <<extend>> Place order (set priority) Extension points: set priority <<include>> inclusion Place rush order inclusion use case Check password Validate user Track order base use case • • extension use case <<include>> common to multiple use cases ; Often no actor may be associated with a ‘used’ use case generalization child use case Retinal scan 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 (http: //www. jeckle. de/files/viewfront. pdf) 109

A Use Case Template (http: //www. bredemeyer. com/pdf_files/use_case. pdf) Use Case Identifier: e. g. , “Withdraw money”; ref # = wm 3; 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 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. List of NFRs that the use case must meet List of issues that remain to be resolved Non-Functional (optional) Issues 110

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 1. 2. 3. 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 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 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? 111

Class Diagrams & Object Diagrams 112

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 11

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: operation. Name(parameter. Name: parameter. Type …): return. Type 11

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

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

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 11

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? 11

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

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 12

Association classes • Sometimes, an attribute that concerns two associated classes cannot be placed in either of the classes • The following are equivalent * Student * Course. Section Registration grade Student * Registration * Course. Section grade 12

Reflexive associations • It is possible for an association to connect a class to itself successor * Course * * is. Mutually. Exclusive. With * prerequisite 12

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 12

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

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

Handling multiple discriminators • Creating higher-level generalization 12

Handling multiple discriminators • Using multiple inheritance Animal type. Of. Food habitat Aquatic. Animal Aquatic. Carnivore Land. Animal Aquatic. Herbivore Carnivore Land. Carnivore Herbivore Land. Herbivore 12

Avoiding having instances change class • An instance should never need to change class 12

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 12

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 13

More Advanced Features: Aggregation • Aggregations are special associations that represent ‘partwhole’ relationships. —The ‘whole’ side is often called the assembly or the aggregate —This symbol is a shorthand notation association named is. Part. Of Vehicle * Vehicle. Part Country * Region 13

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 13

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

Aggregation hierarchy Vehicle * Chassis Body. Panel * Door * Frame Engine Transmission Wheel 13

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 13

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 Person «interface» Cashier Machine withdraw deposit Employee Person Machine Cashier ATM Employee Cashier ATM 13

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 13

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 13

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 *, /, +, - 13

An example: constraints on Polygons {edge->for. All(e 1, e 2 | e 1 <> e 2 implies e 1. start. Point <> e 2. startpoint a Linear. Shape is any shape and e 1. end. Point <> e 2. endpoint)} {ordered} that can be constructed of line segments (in contrast with shapes that contain curves). Linear. Shape edge 1. . * Line. Segment start. Point: Point end. Point: Point length : int Path length Line {edge->size=1} {length = edge. length->sum} Polygon {start. Point <> end. Point} {edge->first. start. Point = edge->last. end. Point} Regular. Polygon {edge->for. All(e 1, e 2 | e 1. length = e 2. length)} 14

Detailed Example: A Class Diagram for Genealogy Person name sex place. Of. Birth date. Of. Birth place. Of. Death date. Of. Death place. Of. Marriage child date. Of. Marraige * date. Of. Divorce parent 2 {parent->for. All(p 1, p 2: p 1 <> p 2 implies p 1. sex <> p 2. sex)} • Problems —A person must have two parents —Marriages not properly accounted for 14

Genealogy example: Possible solutions Person name sex place. Of. Birth date. Of. Birth place. Of. Death child date. Of. Death * partner * 0. . 2 {partner->for. All(p 1, p 2 | p 1 <> p 2 implies p 1. sex <> p 2. sex)} * Union 0. . 1 place. Of. Marriage parents date. Of. Marriage date. Of. Divorce name place. Of. Birth date. Of. Birth place. Of. Death child date. Of. Death * Woman Man female. Partner 0. . 1 * 0. . 1 child * * Union 0. . 1 place. Of. Marriage parents date. Of. Marriage date. Of. Divorce 14

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 14

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 14

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. 14

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 14

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 14

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 14

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 14

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. 15

Actions versus associations • A common mistake is to represent actions as if they were associations Library. Patron * borrow * * Loan return * * Collection. Item Bad, due to the use of associations that are actions * borrowed. Date due. Date * returned. Date Library. Patron Collection. Item Better: The borrow operation creates a Loan, and the return operation sets the returned. Date attribute 15

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 15

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 15

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. Employee Passenger name employee. Number job. Function name number Regular. Flight * supervisor time flight. Number * * Booking seat. Number * * * Specific. Flight date 15

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 15

Exercise: For Airline Reservation System, add any obvious generalizations, making whatever other changes become necessary. Person. Role 0. . 2 Person name id. Number Employee. Role Passenger. Role job. Function Regular. Flight * supervisor time flight. Number * * Booking seat. Number * * * Specific. Flight date 15

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 15

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 15

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 Person. Role 0. . 2 * Person name id. Number * Employee. Role Passenger. Role Airline job. Function Regular. Flight * supervisor time flight. Number * * Booking seat. Number * * * Specific. Flight date 15

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. 16

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 16
![An example (class collaboration) Employee. Role + get. Name [e 2] crew. Member * An example (class collaboration) Employee. Role + get. Name [e 2] crew. Member *](http://slidetodoc.com/presentation_image_h2/4799201610bc75d60f68c39d3307a9e9/image-162.jpg)
An example (class collaboration) Employee. Role + get. Name [e 2] crew. Member * ** Booking [c 2] * * Passenger. Role + make. Booking [c 1] add. Link. To. Booking [c 4] Specific. Flight + specify. Airplane [a 1] + create. Flight. Log [b 1] + change. Airplane [d 1] + find. Crew. Member [e 1] add. Link. To. Booking [c 3] * 0. . 1 Airplane add. Link. To. Specific. Flight [a 2, d 3] delete. Link. To. Specific. Flight [d 2] 0. . 1 Flight. Log [b 2] 16

Class collaboration ‘a’ Making a bi-directional link between two existing objects; e. g. adding a link between an instance of Specific. Flight and an instance of Airplane. 1. (public) The instance of Specific. Flight — 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 Specific. Flight 16

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

Class collaboration ‘c’ Creating an association class, given two existing objects e. g. creating an instance of Booking, which will link a Specific. Flight to a Passenger. Role. 1. (public) The instance of Passenger. Role — 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 Passenger. Role — makes a one-directional link to the instance of Specific. Flight — calls operations 3 and 4. 3. (non-public) The instance of Specific. Flight — makes a one-directional link to the instance of Booking. 4. (non-public) The instance of Passenger. Role — makes a one-directional link to the instance of Booking. 16

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

Class collaboration ‘e’ Searching for an associated instance e. g. searching for a crew member associated with a Specific. Flight that has a certain name. 1. (public) The instance of Specific. Flight — creates an Iterator over all the crew. Member links of the Specific. Flight — for each of them call operation 2, until it finds a match. 2. (may be public) The instance of Employee. Role returns its name. 16

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 16

Example: Specific. Flight class Specific. Flight { private Calendar date; private Regular. Flight regular. Flight; private Terminal. Of. Airport destination; private Airplane airplane; private Flight. Log flight. Log; private Array. List crew. Members; // of Employee. Role private Array. List bookings. . . } 16

Example: Specific. Flight // Constructor that should only be called from // add. Specific. Flight( Calendar a. Date, Regular. Flight a. Regular. Flight) { date = a. Date; regular. Flight = a. Regular. Flight; } 17

Example: Regular. Flight class Regular. Flight { private Array. List specific. Flights; . . . // Method that has primary // responsibility public void add. Specific. Flight( Calendar a. Date) { Specific. Flight new. Specific. Flight; new. Specific. Flight = new Specific. Flight(a. Date, this); specific. Flights. add(new. Specific. Flight); }. . . } 17

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.

- Slides: 173