Скачать презентацию Anyone know what type of planes these are Скачать презентацию Anyone know what type of planes these are

0b403ac5fa791302deec730be903d0c9.ppt

  • Количество слайдов: 86

Anyone know what type of planes these are? Douglas DC-3 © Lethbridge/Laganière 2005 Chapter Anyone know what type of planes these are? Douglas DC-3 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 1

What is this? four-cylinder inline crankshaft with pistons. © Lethbridge/Laganière 2005 Chapter 5: Modelling What is this? four-cylinder inline crankshaft with pistons. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 2

Before beginning any “Large” undertaking, you should ALWAYS build a model first! Question: Before Before beginning any “Large” undertaking, you should ALWAYS build a model first! Question: Before building a house what kind of modeling occurs?

Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 5: Modelling with Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 5: Modelling with Classes Timing: 120 -150 minutes

Announcements How to get the birthday to work in Facebook: …$app_url= Announcements How to get the birthday to work in Facebook: …$app_url="http: //apps. facebook. com/Lreid 2 workshop 2/"; $facebook = new Facebook(array('app. Id' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET_KEY)); $user = $facebook->get. User(); if (!$user) { $login. Url = $facebook->get. Login. Url(array('scope'=>'email, user_birthday, publish_stream', 'redirect_ul'=>$app_url)); echo ""; } else {… Changing Permissions in PHP: • Privacy Settings • Apps • Delete your app How to see the API Graph in Facebook https: //developers. facebook. com/tools/explorer How to see you Apps in Facebook: http: //www. facebook. ca © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 5

5. 1 What is UML? The Unified Modelling Language is a standard graphical language 5. 1 What is UML? 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 objectoriented 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 6

UML diagrams • Class diagrams —describe classes and their relationships • Interaction diagrams —show 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 7

UML features • It has detailed semantics • It has extension mechanisms • It UML features • It has detailed semantics • It has extension mechanisms • It has an associated textual language —Object Constraint Language (OCL) (not covered in cs 2212) The objective of UML is to assist in software development —It is not a methodology © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 8

What constitutes a good model? A model should • use a standard notation • What constitutes a good model? A model should • use a standard notation • be understandable by clients and users • lead software engineers to have insights about the system • provide abstraction Models are used: • to help create designs • to permit analysis and review of those designs. • as the core documentation describing the system. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 9

IMPORTANT Do NOT confuse what we are learning today with the classes that you IMPORTANT Do NOT confuse what we are learning today with the classes that you actually end up building (the class that you write in Java). The classes we learn about today will be the BASIS for those classes but the first class diagram you draw/model for your project will NOT be exactly like what you end up coding. How would Course Section you code it to Course. Number E. G. see the Course. Title Room Time sections of a course? © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 10

5. 2 Essentials of UML Class Diagrams The main symbols shown on class diagrams 5. 2 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 11

Classes A class is simply represented as a box with the name of the 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 12

5. 3 Associations and Multiplicity An association is used to show two classes are 5. 3 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 13

Object Diagrams Object (Instant) Diagrams give a representation of a class diagram using actual Object Diagrams Object (Instant) Diagrams give a representation of a class diagram using actual objects in the system. For example if this is our class diagram: Which of the following object diagrams are valid? Homer Lisa Walmart Sears Bart © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 14

Labelling associations • Each association can be labelled, to make explicit the nature of Labelling associations • Each association can be labelled, to make explicit the nature of the association © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 15

Analyzing and validating associations • Many-to-one —A company has many employees, —An employee can Analyzing and validating associations • Many-to-one —A company has many employees, —An employee can only work for one company. - This company will not store data about the moonlighting activities of employees! —A company can have zero employees - E. g. a ‘shell’ company —It is not possible to be an employee unless you work for a company Employee © Lethbridge/Laganière 2005 * works. For Chapter 5: Modelling with classes 1 Company 16

Analyzing and validating associations • Many-to-many —A secretary can work for many managers —A 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? © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 17

Analyzing and validating associations • One-to-one —For each company, there is exactly one board 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 1 © Lethbridge/Laganière 2005 1 Chapter 5: Modelling with classes 18

Analyzing and validating associations Avoid unnecessary one-to-one associations Avoid this © Lethbridge/Laganière 2005 do Analyzing and validating associations Avoid unnecessary one-to-one associations Avoid this © Lethbridge/Laganière 2005 do this Chapter 5: Modelling with classes 19

Question Label the multiplicities for the following examples: __ __ rented Customer Video __ Question Label the multiplicities for the following examples: __ __ rented Customer Video __ __ currently. Renting Woman Brother League Player __ gives. Birth. Too __ has __ currently. On. Ice. For __ UWO Computer Science Assigned. To __ Child __ Sister __ Hockey Team __ CS 212 20

Question In words, what do these diagrams mean? Country has. Capital 0. . 1 Question In words, what do these diagrams mean? Country has. Capital 0. . 1 1 Person * favourite 0. . 1 City Colour one and only one city as its capital A Country has _____________ A City __________ A Colour ____________ A Person _____________ UWO Computer Science CS 212 21

Another Question: Correctly label this diagrams multiplicity: Car ? ? © Lethbridge/Laganière 2005 listening. Another Question: Correctly label this diagrams multiplicity: Car ? ? © Lethbridge/Laganière 2005 listening. To could. Tune. Into ? Radio Station ? Chapter 5: Modelling with classes 22

A more complex example • A booking is always for exactly one passenger —no 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 23

Question Create two or three classes linked by associations to represent the following situations: Question Create two or three classes linked by associations to represent the following situations: • A landlord renting apartments to tenant • An author writing books distributed by publishers • Label the multiplicities (justify why you picked them) • Give each class you choose at least 1 attribute UWO Computer Science CS 212 24

Your Answer UWO Computer Science CS 212 25 Your Answer UWO Computer Science CS 212 25

Reflexive associations • It is possible for an association to connect a class to Reflexive associations • It is possible for an association to connect a class to itself successor * Course * * * is. Mutually. Exclusive. With prerequisite At Western, you must have CS 2210 and CS 2211 to take CS 2212 © Lethbridge/Laganière 2005 At Western, you can’t take Calc 1301 b and Calc 1501 b Chapter 5: Modelling with classes 26

Association classes • Sometimes, an attribute that concerns two associated classes cannot be placed Association classes • Sometimes, an attribute that concerns two associated classes cannot be placed in either of the classes • The following are equivalent © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 27

Question Add association classes to the following many to many associations and come up Question Add association classes to the following many to many associations and come up with at least one attribute for the new association class: Guest Spectator Player * * * © Lethbridge/Laganière 2005 stay in * Hotel. Room attended * Show * Sports. Game participated in Chapter 5: Modelling with classes 28

5. 4 Generalization Specializing a superclass into two or more subclasses • The discriminator 5. 4 Generalization Specializing a superclass into two or more subclasses • The discriminator is a label that describes the criteria used in the specialization © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 29

Avoiding unnecessary generalizations Inappropriate hierarchy of classes, which should be instances Ask yourself: Does Avoiding unnecessary generalizations Inappropriate hierarchy of classes, which should be instances Ask yourself: Does this class require any operations that will be done differently than the other classes? If answer is no, don’t make it a class! © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 30

Avoiding unnecessary generalizations (cont) Improved class diagram, with its corresponding instance diagram © Lethbridge/Laganière Avoiding unnecessary generalizations (cont) Improved class diagram, with its corresponding instance diagram © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 31

Handling multiple discriminators • Creating higher-level generalization • Say we had a Prey class, Handling multiple discriminators • Creating higher-level generalization • Say we had a Prey class, we would need TWO associations instead of just one. Prey © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 32

Handling multiple discriminators • Using multiple inheritance • Using the Player-Role pattern (in Chapter Handling multiple discriminators • Using multiple inheritance • Using the Player-Role pattern (in Chapter 6) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 33

Avoiding having instances change class • An instance should never need to change class Avoiding having instances change class • An instance should never need to change class • This is a poor model: • A bit better solution, but then we lose the polymorphism advantage for any operations that differ between Full. Time. Student and Part. Time. Student: Student attendance. Status © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 34

5. 5 Object Diagrams • A link is an instance of an association —In 5. 5 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 35

Question: Draw a class diagram corresponding to the following situation: • An organization has Question: Draw a class diagram corresponding to the following situation: • An organization has three categories of employee: professional staff, technical staff and support staff. The organization also has departments and divisions. Each employee belongs to either a department or a division. Assume that people will never need to change from one category to another. UWO Computer Science CS 2212 36

Your Answer: UWO Computer Science CS 2212 37 Your Answer: UWO Computer Science CS 2212 37

Question: Draw a class diagram that could generate the object diagram shown below: is. Question: Draw a class diagram that could generate the object diagram shown below: is. Member. Of United Nations: Canada: is. Member. Of is. Part. Of France: is. Member. Of borders NATO: borders Quebec: is. Member. Of borders Mexico: is. Part. Of borders Ontario: is. Part. Of is. Member. Of New York State: United States: UWO Computer Science CS 2212 38

Your answer: Political. Entity name borders * * Territory Country 1 UWO Computer Science Your answer: Political. Entity name borders * * Territory Country 1 UWO Computer Science * is. Member. Of * is. Part. Of * Inter. Governmental. Organization State. Or. Province CS 2212 39

Associations versus generalizations in object diagrams • Associations describe the relationships that will exist Associations versus generalizations in object diagrams • Associations describe the relationships that will exist between instances at run time. —When you show an instance diagram generated from a class diagram, there will be an instance of both classes joined by an association • Generalizations describe relationships between classes in class diagrams. —They do not appear in instance diagrams at all. —An instance of any class should also be considered to be an instance of each of that class’s superclasses © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 40

5. 6 More Advanced Features: Aggregation • Aggregations are special associations that represent ‘part-whole’ 5. 6 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 is. Part. Of © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 41

When to use an aggregation As a general rule, you can mark an association 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 NOTE: Might be able to say a person is part of a club BUT the owner of the club does NOT own the members Club © Lethbridge/Laganière 2005 1 * Member Chapter 5: Modelling with classes 42

Composition • A composition is a strong kind of aggregation —if the aggregate is 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 43

Propagation • A mechanism where an operation in an aggregate is implemented by having 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 —Eg. Deleting a polygon means deleting the line segments • Marking a part-whole association as an aggregation using the diamond symbol is optional. Leaving it as an ordinary association is not an error, whereas marking a non-aggregation with a diamond is an error, therefore, when in doubt, leave it out! © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 44

Question For each of the following associations, indicate whether it should be an ordinary Question For each of the following associations, indicate whether it should be an ordinary association a standard aggregation a composition a) A telephone and its handset b) A school and its teachers c) A book and its chapters © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 45

Interfaces An interface describes a portion of the visible behaviour of a set of 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 • Although Employee and ATM share common operations they have different superclasses. This means they cannot be put in the same inheritance hierarchy; therefore the interface called Cashier is used • A key advantage of using interfaces is that they can reduce what is called coupling between classes. • Inheritance indicates an isa relationship, interfaces indicate a can-be-seenas relationship Person «interface» Cashier Machine withdraw deposit Employee © Lethbridge/Laganière 2005 Person Machine Cashier ATM Employee Chapter 5: Modelling with classes Cashier ATM 46

5. 9 The Process of Developing Class Diagrams You can create UML models at 5. 9 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 47

System domain model vs System model • The system domain model omits many classes 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 such as the database, files, servers, clients —Utility classes © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 48

Suggested sequence of activities • Identify a first set of candidate classes • Add 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 (Chapter 6) Don’t be too disorganized. Don’t be too rigid either. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 49

Identifying classes • When developing a domain model you tend to discover classes • 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 50

A simple technique for discovering domain classes • Look at a source material such 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. For example in a domain model, you would eliminate classes that represent command or menus in the UI. As a rule of thumb, a class is only needed in a domain model if you have to store or manipulate instances of it in order to implement a requirement • Pay attention to classes in a domain model that represent types of users or other actors © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 51

Identifying associations and attributes • Start with classes you think are most central and 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 52

Tips about identifying and specifying valid associations • An association should exist if a 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 53

Actions versus associations • A common mistake is to represent actions as if they Actions versus associations • A common mistake is to represent actions as if they were associations Bad, due to the use of associations that are actions © Lethbridge/Laganière 2005 Better: The borrow operation creates a Loan object and the return operation set the returned. Date attribute Chapter 5: Modelling with classes 54

Identifying attributes • Look for information that must be maintained about each class • 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 55

Tips about identifying and specifying valid attributes • It is not good to have 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 Person name addresses Bad due to a plural attribute Person name street 1 municipality 1 prov. Or. State 1 country 1 postal. Code 1 street 2 municipality 2 prov. Or. State 2 country 2 postal. Code 2 name Address 1* * addresses street municipality prov. Or. State country postalcode type Good solution. The type indicates whether it is a home address, business address etc. Bad due to too many attributes, and inability to add more addresses © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 56

An example (attributes and associations) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 57 An example (attributes and associations) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 57

Identifying generalizations and interfaces • There are two ways to identify generalizations: —bottom-up - 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 58

An example (generalization) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 59 An example (generalization) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 59

For the first Class Diagram you are to design… REMEMBER: you are only supposed For the first Class Diagram you are to design… REMEMBER: you are only supposed to represent the data that needs to be saved to memory. THIS IS IMPORTANT! (don’t represent helper classes!) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 60

Case Study of Boogle Implement the game http: //www. hasbro. com/scrabble/en_US/boggle. Game. cfm Some Case Study of Boogle Implement the game http: //www. hasbro. com/scrabble/en_US/boggle. Game. cfm Some Specs: • There are 3 modes: admin mode, tournament mode, fun play mode • To get into admin mode type: java UWOBoggle -admin • To get into tournament mode or fun play mode type: java UWOBoggle — Then select Tournament or Fun Play • In admin mode must be able to • Manage players: • Add, delete and modify players. Players have a first name, last name, userid and password. Player C Player A • Sort players by first and last name Player B Winner • Reset password Player B • Manage puzzles (puzzles are made up of 16 letters and puzzleid) • Add, delete, bulkload, solve (using a stored dictionary of valid words) and list by puzzleid • Manage tournaments (2 -8 players per tournament, tournament has a unique tournament id and a name. A tournaments run in 1 -3 battles of 2 per round, winning player moves to the next round) • Add tournaments • Add players to a tournament, add puzzles (all players play the same puzzle on each round but in pairs, higher scorer for each pair moves to the next round, in odd numbers, the highest scorer get a buy to the next round) to a tournament (must keep track of the score for each player for each round and the winner of each pairing) • Delete tournaments • List tournaments by tournament id or by tournament name • Print tournaments © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 61

More Specs • In Tournament or Fun Play Mode a user must be able More Specs • In Tournament or Fun Play Mode a user must be able to: • Log on (gets 3 attempts and then kicked out) • Play puzzles as follows • Start the puzzle • Given 3 minutes to find words • Given a score at the end • If the puzzle is not a tournament puzzle, the player can see the solution for the puzzle. • In just Tournament Mode • Player sees a list of tournaments that he/she is participating in • Picks an ongoing tournament • List completed tournaments • Plays the puzzles • Sees if he/she moves to the next round • In just Fun Mode • Pick a puzzle from the list of puzzles • Play the puzzle • View the top 3 scores for that puzzle • See the top 3 players (who have the highest scores for any games) Working in pairs, determine the nouns and noun phrases that might, in the end, become potential classes. Add the attributes and associations. While making your list, choose good names for each of the potential classes REMEMBER you only need classes in the domain model for things that need to have data stored about them! © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 62

Your Answer UWO Computer Science CS 212 63 Your Answer UWO Computer Science CS 212 63

Laura’s Use Case Diagram for the Project © Lethbridge/Laganière 2005 Chapter 5: Modelling with Laura’s Use Case Diagram for the Project © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 64

Laura’s Class Diagram for the Project © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes Laura’s Class Diagram for the Project © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 65

One group’s class diagram for the project. This one has problems…Can you see them? One group’s class diagram for the project. This one has problems…Can you see them? © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 66

The remaining class diagrams made by the groups that year: © Lethbridge/Laganière 2005 Chapter The remaining class diagrams made by the groups that year: © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 67

© Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 68 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 68

© Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 69 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 69

© Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 70 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 70

© Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 71 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 71

Allocating responsibilities to classes A responsibility is something that the system is required to 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 72

Categories of responsibilities • Setting and getting the values of attributes • Creating and 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 73

An example (responsibilities) • Creating a new regular flight • Searching for a flight An example (responsibilities) • Creating a new regular flight • Searching for a flight • Modifying attributes of a flight • Creating a specific flight • Booking a passenger • Canceling a booking © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 74

Prototyping a class diagram on paper • As you identify classes, you write their Prototyping a class diagram on paper • 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 75

Identifying operations Operations are needed to realize the responsibilities of each class • There 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 76

An example (class collaboration) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 77 An example (class collaboration) © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 77

Class collaboration ‘a’ Specific. Flight * 0. . 1 Airplane Making a bi-directional link Class collaboration ‘a’ Specific. Flight * 0. . 1 Airplane 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 78

Class collaboration ‘b’ 1 Creating an object and linking it to an existing object Class collaboration ‘b’ 1 Creating an object and linking it to an existing object e. g. creating a Flight. Log, and linking it to a Specific. Flight. 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 79

Class collaboration ‘c’ 1 1 Creating an association class, given two existing objects e. Class collaboration ‘c’ 1 1 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 80

Class collaboration ‘d’ Changing the destination of a link e. g. changing the Airplane 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 81

Class collaboration ‘e’ Searching for an associated instance e. g. searching for a crew 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. © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 82

5. 10 Implementing Class Diagrams in Java • • Attributes are implemented as instance 5. 10 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 © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 83

Example: Specific. Flight (implementing the ONE side in a one to many relationship) class Example: Specific. Flight (implementing the ONE side in a one to many relationship) class Specific. Flight { private Calendar date; private Regular. Flight regular. 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; } } © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 84

Example: Regular. Flight (implementing the MANY side in a one to many relationship) class Example: Regular. Flight (implementing the MANY side in a one to many relationship) class Regular. Flight { private 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); } . . . } © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes 85

Automating UML Class Diagrams http: //www. youtube. com/watch? v=v 3 -ozq-Zb. HE&feature=related © Lethbridge/Laganière Automating UML Class Diagrams http: //www. youtube. com/watch? v=v 3 -ozq-Zb. HE&feature=related © Lethbridge/Laganière 2005 Chapter 5: Modelling with classes