chapter 2-part ii structural model: class/object diagram object-oriented system analysis and design
TRANSCRIPT
Chapter 2-Part II Structural Model:
Class/Object diagram
Object-Oriented System Analysis and Design
RecallThe UML-
The why? and the principle of modeling
The diagramsFunctional Model
Essential/system usecaseUse case components; Actors,Use cases,BoundaryAnd Relationship
Introduction
3
Modelling a system involves identifying the things that are important to your particular view.
These things form the vocabulary of the system you are modelling.
This part explores how we do basic modelling of things and concepts from the real-worldusing Class Diagrams
Before learning how to model using Class Diagram, we must first understand the basic building blocks of Class Diagram
Cont…A class is a definition of objects that share the same properties, relationships and behavior.
An object is an instance of a class.
The properties of a class are called attributes and the behavior is expressed in operations.
4
Cont…Class diagrams are widely used to describe the types of objects in a system and their relationships.
The relationship can be inheritance, aggregation and association.
The class model also describes the attributes and operations of the class along with the visibility of each.
5
Cont…Class diagrams model class structure and contents using design elements such as classes, packages and objects.
Class diagrams are used in nearly all Object Oriented software designs.
They are used to describe the Classes of the system and their relationships to each other.
6
Common Uses
7
Class diagrams are used to model the static design view of a systemsupports the functional requirements of the
systemWhen we model the static design view of a
system, we will use class diagrams in 3 ways: -To model the vocabulary of the system
involves making a decision about which abstractions are a part of the system under consideration and which falls outside its boundaries
Class diagrams are used to specify these abstractions and their responsibilities
8
To model simple collaborationsA collaboration is a society of classes,
interfaces, and other elements that work together to provide some co-operative behaviour that is bigger than the sum of all the elements
Class diagrams are used to visualize and specify this set of classes and their relationships
To model logical database schemaClass diagrams can also be used to model
schemas for databases used to store persistent information
Forward & Reverse Engineering
9
Even though modelling is important, the primary product of a development team is software, not diagrams
Therefore, it is important that the models we create and the implementations we deploy map to one another
In most cases, the models we create will be mapped to code
10
Forward engineering is the process of transforming a model into code through a mapping to an implementation language
Reverse engineering is the process of transforming code into model through a mapping from a specific implementation language
Cont…The UML was designed with such mappings in mindEspecially true for class diagrams, whose contents have a clear mapping to object-oriented languages, i.e Java, C++, etc
11
Cont…To start with class modeling, identify
objects and classes, prepare a data dictionary, identify associations between objects, identify class attributes and initial set of operations and then organize object classes using inheritance. (more on this later)
This process can be initiated from CRC model.
12
Cont…
13
Domain Modeling Using CRC
14
Class Responsibility Collaboration (CRC cards) ◦ are a brainstorming tool used in the design
of object-oriented software. ◦ are typically used when first determining
which classes are needed and how they will interact.
◦ CRC are an index card on which one records the responsibilities and collaborators of classes, thus the name, which stands for Class-Responsibility-Collaboration.
Cont…A class responsibility collaborator model
is a collection of standard index cards that have been divided into three sections. A class represents a collection of similar objects,
a responsibility is something that a class knows or does, and
a collaborator is another class that a class interacts with to fulfill its responsibilities.
Cont..CRC cards are usually
created from index cards on which are written:
The class nameThe responsibilities of
the class.The names of other
classes with which the class will collaborate to fulfill its responsibilities.
Cont…Although CRC cards were originally
introduced as a technique for teaching object-oriented concepts, they have also been successfully used as a full- fledged modeling technique.
CRC models are an incredibly effective tool for conceptual modeling as well as for detailed design.
Basic stepsBrainstorm with SMEIteratively do the following
Find classesFind responsibilitiesDefine collaborators
Class model: major conceptsObjectsClasses
NameAttributeoperations
Objects
20
An object is simply a real-world thing or concept
Three essential aspects of objects are:An object has an identity
Can have a name or can be anonymousAn object has state
the names of the various properties that describe the object (attributes) and also the value of those attributes
An object has behaviourrepresented by functions (or methods) that use or
change the values of the object’s attributesAn object is an instance of a class
Classes
21
Classes are the most important building block of any object-oriented system
Classes are used to: -capture the vocabulary of the system you are
developing represent software things, hardware things, and
even things that are purely conceptualWell-structured classes have crisp boundaries
and form a part of a balanced distribution of responsibilities across the system ClassName
attributes
operations
Name
22
Every class must have a name to distinguish it from other classescan be a simple name, i.e. Student, Door, etc
can be a path name the class name prefixed by the name of the
package in which that class lives, i.e. BusinessRecord::Customer,
A class may be drawn showing only its name
Customer
Attribute
23
An attribute is a named property of a class that describes a range of values that instances of the property may holdrepresents some property of the thing you are
modelling that is shared by all objects of that class
At any given moment, an object of a class will have specific values for every one of it’s class attributes
A class may have a number of attributes
24
Attributes may be drawn showing only their names (a)
Or, we can further specify an attribute by stating its type and possibly a default initial value (b)
CustomerCustomer
namename addressaddress phonephone birthdatebirthdate
WallWall
height : Floatheight : Float width : Floatwidth : Float thickness : Floatthickness : Float isLoadBearing : Boolean isLoadBearing : Boolean = false= false
(a) (b)
Operation
25
An operation is the implementation of a service that can be requested from any object of the class to affect behaviourOften, invoking an operation on an object changes the object’s data or state
A class may have a number of operations or no operations at all
26
Operations may be drawn showing only their names (a)
We can further specify an operation stating its signature (b)including the name, type and default value of all
parameters and (in case of functions) a return type
CustomerCustomer
add()add() remove()remove() edit()edit()
TemperatureSensorTemperatureSensor
reset()reset()setAlarm(t : setAlarm(t : Temperature)Temperature) value() : value() : TemperatureTemperature
(a) (b)
Cont…Attributes define the properties of the objects:
every instance of the class has the same attributes
an attribute has a data typean attribute has visibility (private, protected, public)
the values of the attributes may differ among instances
27
Cont…Operations define the behavior of the objects
oaction performed on or by an object
oavailable for all instances of the class
omethods/operations has visibility (private, protected, public)
oneed not be unique among classes
Cont…
29
30
HINTS!When we model classes, a good starting point
is to specify the responsibilities of the things in our vocabulary
A class may have any number of responsibilitiesWe do not want any one class to have too many or
too little responsibilitiesIn practice, every well-structured class has at least
one responsibility or at most, just a handfulWe will then translate these responsibilities
into a set of attributes and operations that best fulfil the class’s responsibilities
A simple example
31
On-line Bookstore Reviewa web application that can be accessed by the
store’s registered customer, whereby each customer can review one or more books sold in the book store
The process: -Each registered customer has an account that is used to
verify his/her ID and passwordEach registered customer, upon account verification, can
review one or more books based on its title.
Problem: Come up with a set of classes that can be found in the above problem
32
Things that are found in the problem: -The process: -
Each registered CUSTOMER has an ACCOUNT that is used to verify his/her ID and password
Each registered CUSTOMER, upon ACCOUNT verification, can REVIEW one or more BOOKS based on its title.
Therefore, the things identified are: -AccountCustomerBookReview
33
Each of these things can form individual classes with responsibilitiesAccount
Used to keep the customer’s ID and password for verifying that the customer is a registered customer
Also keeps additional information, i.e. e-mail addressCustomer
Used to keep information about the customer, such as customer’s name, ID, address etc
BookUsed to keep the relevant information on the book that is
crucial to customer’s review, i.e. book title, author, ratingReview
Used to assign ratings to book reviewed (with 1 being the lowest and 5 the highest)
Used to compute the average rating for each book that has been reviewed
34
Translate the responsibilities for each class into attributes and operations needed to perform those responsibilities (relevant to the given problem)Account
Attributes: emailAddress, ID, passwordOperations: verifyPassword()
CustomerAttributes: CustName, CustAddress, CustID etcOperations: NONECan choose not to show the attributes when modelling the
class as they are not relevant to the given problemBook
Attributes: title, author, ratingOperations : NONE
ReviewAttributes: NONEOperations: assignRatings(rating : Int),
computeAvgRating() : double
35
Model the classes: -
AccountAccount
emailAddressemailAddress IDID passwordpassword
verifyPassworverifyPassword()d()
BookBook
title : title : StringString
author: author: StringString
rating: rating: FloatFloat
ReviewReview
assignRating(rating : Int)assignRating(rating : Int)
computeAvgRating() : computeAvgRating() : DoubleDouble
Customer
Summary
36
Attributes, operations and responsibilities are the most common features needed to convey the most important semantics of our classesWe may need to extend our classes by specifying
other features : will be covered in later Classes rarely stand alone
When we build models, we will focus on groups of classes that interact with one another (relationships)
In the UML, these group of classes form collaborations and are usually visualized in class diagrams
Relationships
RelationshipsA relationship is, a general term, covering
the specific types of logical connections found on class diagrams.
A Link is the basic relationship among objects.
It is represented as a line connecting two or more object boxes.
A link is an instance of an association. In other words, it creates a relationship between two classes.
38
Cont…
39
When we build abstractions, we will discover that very few classes stand alonemost of them collaborate with others in a
number of waysTherefore, when we model a system, we
mustidentify the things that form the vocabulary of
our system (classes)model how these things stand in relation to
one anotherIn UML, the ways that things can connect
to one another, either logically or physically, are modelled as relationships
40
In object-oriented modelling, there are three kinds of relationships that are most importantDependencies
represents ‘using’ relationship among classesGeneralizations
connects generalized classes to more specialized ones in what is known as subclass/super-class or child/parent relationship (inheritance)
Associationsrepresents structural relationships among
instances/objectsEach of these relationships provides a different way of combining our abstractions (classes)
41
The UML provides a graphical representation for each of these kinds of relationshipsallows us to visualize relationships emphasize the most important parts of a relationship: its name, the things it connects, and its properties
Dependency
42
A dependency is a using relationship that states that a change in specification of one thing (independent thing) may affect another thing that uses it (dependent thing), but not necessarily the reverse
It is rendered as a dashed directed line
dependent independent
43
Dependencies are used in the context of classes to show that one class uses another class as an argument in the signature of an operationif the used class changes, the operation of the
other class may be affectedThe most common kind of dependency
relationship is the connection between a class that only uses another class as a parameter to an operation
Cont…
To model dependencyCreate a dependency pointing from the class with the operation to the class used as a parameter in the operation
44
45
Example: - A system that manages the assignment of students and instructors to courses in a university
CourseScheduleCourseSchedule
add(c : Course)add(c : Course) remove(c : remove(c : Course)Course)
Course
There’s a dependency from CourseSchedule to Course, as Course is used in both the add() and remove() operations of CourseSchedule
Generalization
46
A generalization is a relationship between a general thing (superclass or parent) and a more specific kind of that thing (subclass or child)
Generalization means that objects of the child may be used anywhere the parent may appear, but not the reversethe child is substitutable for the parent
Cont…It supports polymorphism
An operation of the child that has the same name/ signature as an operation in a parent overrides the operation of the parent
47
48
Graphically, a generalization is rendered as a solid directed line with a large open arrowhead, pointing to the parent
ChildClassChildClass
attributesattributes
operationsoperations
ParentClass
49
A class may have zero, one or more parentA class that has no parent and one or more
children is called a root or base classA class that has no children is called a leaf
classA class that has exactly one parent is said to
use single inheritanceA class that has more that one parent is said to
use multiple inheritanceA given class cannot be its own parent
We will often use generalizations among classes and interfaces to show inheritance relationships.can also create generalizations with packages
50
To model inheritance relationshipGiven a set of classes, look for responsibilities,
attributes and operations that are common to two or more classes
Elevate those common responsibilities, attributes and operations to a more general class. If necessary, create a new class to which you can assign these elements
Specify that the more-specific classes inherit from the more-general class by placing a generalization relationship that is drawn from each specialized class to its more-general parent
51
Example: - The Rectangle, Circle and Polygon classes inherits from the attributes and operations of the Shape class
ShapeShape
originorigin
move()move() resize()resize() display()display()
RectangleRectangle
corner : corner : PointPoint
CircleCircle
radius : Floatradius : Float
PolygonPolygon
points : Listpoints : List
display()display()
Association
52
An association is a structural relationship that specifies that objects of one thing are connected to objects of anotherwe can navigate from an object of one class
to an object of the other class, and vice versaTypes of association: -
Unary associationwhere both ends of an association circle back to
the same classBinary association
connects exactly two classesN-ary association
connects more than two classes
53
Graphically, an association is shown as a solid line connecting the same or different classes
54
There are 4 adornments that apply to associations: -Name
An association can have a name to describe the nature of the relationship
A direction can also be given to the name by providing a direction triangle that points in the direction intended (to read the name)
Person CompanyWorks for
name name direction
association
55
RoleWhen a class participates in an
association, it has a specific role that it plays in the relationship
A role is just the face that the class at the near end of the association presents to the class at the other end of the association
An explicit name can be given to the role a class plays in an association
Person Companyemployee employer
role name
association
56
MultiplicityIt is important to state how many objects may
be connected across an instance of an association
This “how many” is called multiplicity of an association’s role
It is written as an expression that evaluates to a range of values or an explicit value
Multiplicity can be written as multiplicity ofexactly one (1)zero or one (0..1)many (*)
• one or more (1..*)• exact numbers, i.e 3
Person Companyemployee employer
1..* *
multiplicity
57
Aggregationis a “whole-part” relationship within which one or
more smaller class are “part” of a larger “whole”represents a “has-a” relationship, whereby an
object of the whole class has objects of the part
Company
Department
1
*
whole
part
aggregation
58
Association ClassesSometimes in an association between two
classes, the association itself might have properties
In the UML, you’ll model this as an association class, which is a modeling element that has both association and class propertiesIt is used to model an association that has
characteristics of its own outside the classes it connects
It comes in handy when you have many-to-many relationship that you would like to break into a set of one-to-many relationships
Warning: You cannot attach an association class to more than one association
59
UML represents an association class with a regular class box and a dashed line that connects the association class to the association between the other two classes.
CompanyCompany PersonPersonemployeremployer employeeemployee
descriptiondescription dateHireddateHired salarysalary
JobJob
** 1..*1..*
association classassociation class
60
Example: There’s a many-to-many relationship between Author and Book, whereby an Author may have written more than one book and a Book may have more than one Author. The presence of the BookAndAuthor association class allows us to pair one Author with one Book: the role attribute allows us to state whether the Author was the primary, or supporting author, or editor or etc
Author
BookAndAuthBookAndAuthoror
role: Stringrole: String
* 1..* BookBook
title: title: StringString
61
To model structural relationship (association): -For each associations, specify a multiplicity
If one of the classes in an association is structurally or organizationally a whole compared with the classes at the other end that look like parts, use an aggregation
If there’s a many-to-many relationship between two classes, use association class (if possible)
Modelling Relationships
62
When modelling relationships in the UMLUse dependencies only when the relationship is
not structuralUse generalization only when the relationship is
an “is-a-kind-of” or inheritance relationshipBeware of introducing cyclical generalization
relationshipsKeep generalization relationships generally
balanced where the level of inheritance should not be too deep
Use associations only when there are structural relationships among objects
A simple example
63
On-line Bookstore Reviewa web application that can be accessed by the
store’s registered customer, whereby each customer can review one or more books sold in the book store
The process given: -Each registered CUSTOMER has an ACCOUNT that is used
to verify his/her ID and passwordEach PASSWORD entered must be more than 8 characters
and consists of a combination of text and numbersEach registered CUSTOMER, upon ACCOUNT verification,
can REVIEW one or more BOOKs based on its titleA REVIEW can either be a customer’s review and editor’s
review
64
Things that are found in the problem: -AccountPasswordCustomerBookReview
can be divided into CustomerReview and EditorialReview
Cont…Each of these things can form individual classes with responsibilitiesAccount
Used to keep the customer’s ID and password for verifying that the customer is a registered customer
Also keeps additional information, i.e. e-mail address
The password is of the type PASSWORD65
66
PasswordUsed to check that the password entered is
valid (more than 8 characters and consists of combination of text and numbers)
CustomerUsed to keep information about the customer,
such as customer’s name, ID, address etcBook
Used to keep the relevant information on the book that is crucial to customer’s review, i.e. book title, author, rating
Cont…Review
Divided into sub-classes: CustomerReview and EditorialReview
CustomerReviewUsed to assign ratings to book reviewed (with
1 being the lowest and 5 the highest) by customer
Used to compute the average rating for each book that has been reviewed by customer
EditorialReviewUsed to store editor’s review
67
68
Translate the responsibilities for each class into attributes and operations needed to perform those responsibilities (relevant to the given problem)Account
Attributes: emailAddress(string), ID(string), passwd(Password)Operations: verifyPassword(p: Password)
PasswordAttributes: passwd(string)Operations: checkPassword()
CustomerAttributes: CustName, CustAddress, CustID etcOperations: NONECan choose not to show the attributes when modeling the
class as they are not relevant to the given problem (put NONE for both)
BookAttributes: title, author, ratingOperations : NONE
69
ReviewAttributes: NONEOperations: NONE
CustomerReviewAttributes: NONEOperations: assignRatings(rating : Int),
computeAvgRating() : doubleEditorialReview
Attributes: NONEOperations: NONE
70
The relationship between classes: -Dependency
The operation verifyPassword in Account class has as parameter a Password class
Therefore, Account depends on Password Generalization
Review can be divided into customer’s review and editor’s review
Therefore, CustomerReview and EditorialReview is the subclass of Review
71
AssociationA customer can open 1 account and an account can be opened by 1 customer
A customer writes a review and a review can be written by a customer
1 customer can write 1 or many reviews, but 1 review can only come form 1 customer
A book can have many reviews but a review is for one book
72
Modelling the classes and relationships: -
BookBook
title : title : StringString
CustomerReviewCustomerReview
assignRating(rating : Int)assignRating(rating : Int)
computeAvgRating() : computeAvgRating() : DoubleDouble
Customer
Review
EditorialReview
writes is written by
1 1..*
has
1 *
AccountAccount
emailAddress : stringemailAddress : string ID : stringID : string passwd : Passwordpasswd : Password
verifyPassword(p : verifyPassword(p : Password)Password)
PasswordPassword
pass : Stringpass : String
checkPassworcheckPassword()d()
opens1
1
Summary
73
Plain, unadorned dependencies, generalizations and associations with names, multiplicities and roles are the most common features needed in creating abstractions (classes)For most of the models that we will build, the basic form of these three relationships will be all that is needed to convey the most important semantics of a relationship
Cont…Dependencies, generalizations and associations are all static things defined at the level of classes
In UML, these relationships are usually depicted in class diagrams
74
Example
75
Littlesand, Pebblesea and Mudport are three charming resorts on the South Coast which are very popular with tourists, since they score well on beach rating and hours of sunshine for the area. All three resorts have a large number of places to stay, ranging from one-room guest house to the exclusive Palace Hotel at Pebblesea. The local tourist board wants to set up a central system to deal with room bookings in the area.
Draw a class diagram to represent this information. Where appropriate, your diagram should include association, aggregation, inheritance and multiplicity. List sample attributes and operations ONLY for the class Resort.
76
Steps in drawing the Class Diagram: -Find the abstractions/classes
Littlesand, Pebblesea and Mudport are three charming resorts on the South Coast which are very popular with tourists, since they score well on beach rating and hours of sunshine for the area. All three resorts have a large number of places to stay, ranging from one-room guest house to the exclusive Palace Hotel at Pebblesea. The local tourist board wants to set up a central system to deal with room bookings in the area.
The classes are: -RESORT, PLACE TO STAY, HOTEL, GUEST HOUSE, ROOM, BOOKING & TOURIST
77
Can ignore each classes responsibilities as the question only wants the attributes and operations for the Resort class. (follow the PROBLEM DOMAIN)Resort Class
Used to store information on the resort such as name, description, beach rating, hours of sunshine etc
Used to perform operations such as updating the beach rating and updating the hour of sunshine etc
Attributes: name (string) description (string)beach rating (double) hour of sunshine (double)
Operations:update beach rating update hours of sunshine
78
Find the relationships between the classes: -“All three Resorts have a large number of places
to stay”Places to stay is ‘a part of’ Resorts, with Resort
being the ‘whole’ : AGGREGATIONA resort can have 1 or many places to stay
“All three resorts have a large number of places to stay, ranging from one-room guest house to the exclusive Palace Hotel at Pebblesea”Places to stay consists of guest houses and
hotels, with Places to stay being the parent and the other two, the child : GENERALIZATION
79
“The local tourist board wants to set up a central system to deal with room bookings in the area”ASSOCIATION: -A place to stay has one of many roomsA room can be have many bookings or none
A booking is for one or more roomsA booking can be done by one or many tourists
A tourist can book one or many rooms
80
The class diagram : -
ResortResort
Place_to_StayPlace_to_Stay
HotelHotel Guest_HouseGuest_House
RoomRoom BookingBooking
TouristTourist
1..*
1..* 1..*
1..*
1..*
0..*1
81
The attributes and operations for the Resort class
ResortResort
name : Stringname : String description : Stringdescription : String beach_rating : Doublebeach_rating : Double hours_of_sunshine: Doublehours_of_sunshine: Double
update_beach_rating (r : update_beach_rating (r : Double)Double) update_hours_of_sunshine (h : update_hours_of_sunshine (h : Double)Double)
82
Note: Using forward engineering, the Resort class can now be mapped into a C++ code.class Resort
{ private:
char name[20], descrp[100];double rating, sun_hours;
public:void updateBeachRating(double r) { rating = r; }void updateHoursSunshine(double h) {sun_hours = h;
}};
Object diagrams
Object Diagrams
84
Object diagrams model the instances of things contained in class diagrams
An object diagram shows a set of objects and their relationships at a point in time
You use object diagrams to model the static design view or static process view of a system.involves modelling a snapshot of the system at a moment in time and rendering a set of objects, their state, and their relationships
85
The UML notation for an object takes the same form as that for a class, except for 3 differences:Within the top compartment of the class box, the
name of the class to which the object belongs to appears after a colon :The object may have a name that appears before the colon,
or it may be anonymous (no name before the colon)The contents of the top compartment are underlined
for an object.Each attribute defined for the given class has a
specific value for each object that belong to that class.
Object : Class attribute1 = value attribute2 = value
: Class attribute1 = value attribute2 = value
named object
anonymous object
86
Object diagrams commonly containobjectslinksmay contain notes and constraintsmay also contain packages or subsystems, both
of which are used to group elements of your model into larger chunks
You use object diagrams to model the static design view or static process view of a system just as you do with class diagrams, but from the perspective of real or prototypical instancesSupports the functional requirements of a system
87
Example: From the class diagram given below, you can get several instances of it.
name : Stringname : String
AuthorAuthor
title : Stringtitle : String rating: Doublerating: Double
BookBookwrote
name : Stringname : String
PublisherPublisher
published by
88
name : “Margeret Mitchell”name : “Margeret Mitchell”
: Author: Author
title : “Gone With the Wind”title : “Gone With the Wind” rating: 4.5rating: 4.5
: Book: Bookwrote
name : “Hawthorne”name : “Hawthorne”
AW: PublisherAW: Publisher
published by
Object diagram
89
name : “Tim Burton”name : “Tim Burton”
: Author: Author
title : “Burton on Burton”title : “Burton on Burton” rating: 4rating: 4
: Book: Bookwrote
name : “Barnes”name : “Barnes”
AW: PublisherAW: Publisher
published by
Object diagram
ExerciseAn international airport requires a system to keep track of flight details for customers. For each flight the system needs to store the flight number, destination, departure time, departure gate, airline and flight cost. Some flights are direct flights, i.e. they fly non-stop to the destination and some fly via another airport to their destination. We will call these flights indirect flights. In this case the flight stops at an airport en route to its destination to refuel. In the case of indirect flights information regarding the transit airport must also be stored. The flight cost is calculated to be the cost charged by the airline per customer plus a percentage of this amount (the profit_rate). In the case of indirect flights an additional levy must be added to this amount per customer in order to cover refuelling levies at the transit airport. Furthermore, on some flights additional passengers can board the plane at the transit airport. The system needs to keep track of whether boarding will take place at the transit airport or not. The system also needs to store details of the aircraft used for a flight. The aircraft make, model and capacity (number of passengers that it can carry), must be stored for each aircraft.