630 likes | 757 Views
SYSC 3100 System Analysis and Design. Class Diagrams: Defining relationships between classes . Objectives. To learn how to use the different relationships in a class diagram. They are: Association Aggregation (although don’t worry about this one too much) composition Generalization
E N D
SYSC 3100 System Analysis and Design Class Diagrams: Defining relationships between classes
Objectives • To learn how to use the different relationships in a class diagram. They are: • Association • Aggregation (although don’t worry about this one too much) • composition • Generalization • Realization (interfaces) • Dependency • To develop software using the Open-Closed Principle.
Associations • Association: a structural relationship that specifies that objects of one class are connected to objects of another • An association describes a group of links (semantic connection among objects) with common structure and semantics • Associations represent: • The possibility of a logical relationship or connection between objects of one class and objects of another • If two objects can be linked, their classes have an association • Mathematically correspond to a set of tuples (Relation) • Can be implemented in many ways, depending on the programming language. • Graphically: a solid line connecting the same or different classes
Associations Refining the semantics of an association using: • Basic features • A name • Multiplicities • A role • A navigation • Aggregation and composition adornments • Advanced features • Visibilities • Qualifications • Interface specifier • Arity • Association classes • Constraints
Association name • The name of an association describes the nature of the relationship • You can give a direction to a name by providing a direction triangle that points in the direction you intend to read the name • Works-for Person Dan Goldin NASA Employs Works-for Bill Gates Microsoft John Smith Rockwell ... Organization ...
Association multiplicity • Limit the number of instances of one class that may be related to an instance of another • Define the allowed number of links between objects 1..* 1 Class Class exactly one mandatory (one or more) 0..* Class many (zero or more) 0..1 2..4, 6..8 Class Class numerically specified optional (zero or one)
Meaning of Multiplicity Constraints teaches 1 * Course Professor Professor Dr. Jones Dr. White Dr. Brown Dr. Smith teaches Dr. White CSCI3233 Dr. Smith CSCI4432 CSCI4432 Dr. Brown SWEN5232 SWEN5233 CSCI3233 SWEN5232 Dr. Brown SWEN5233 Course
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
Layer LayerElement -layerElements:Set -containedIn:Layer +elements() +getLayer() +addElement(le) +setLayer(l) +removeElement(le) Example Implementation in Java Layer LayerElement 1 *
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?
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
Analyzing and validating associations • Avoid unnecessary one-to-one associations Avoid this do this
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
Multiplicity Examples Professor Department heads 0..1 1 name subject name 1 teaches * Student Course studies 1..* 4..6 name number title
Multiplicity: Snapshot versus History ? • What is the scope of multiplicity constraints ? • Should they cover past, present and future or just present ? • Answer depends on the context married_to 0..* 0..* Man Woman => when a history of marriages is useful (e.g., police) married_to 0..1 0..1 Man Woman => when only current marital status needed (e.g., bank)
Roles • Correspond to one end of an association • Each end of an association may be assigned a role which serves as its unique identifier • Provide a way of traversing a binary association from one object to a set of related objects (more in the section on the Object Constraint Language) • Are written next to the association line
Roles • A Personplaying the role of employee is associated with a Company playing the role of employer. • An Astronaut playing the role of mission specialist is associated with instances of Experiment. Person Company employee employer conducts 0..* 1..* Astronaut Experiment mission_specialist
Reflexive associations • It is possible for an association to connect a class to itself successor * Course isMutuallyExclusiveWith * * * prerequisite For example, use a reflexive associations for a linked list.
Advert Campaign Example: Associations Association Association role Client StaffMember companyAddress staffContact staffName companyEmail liaises with staffNo companyFax staffStartDate companyName companyTelephone Association name Direction in which name should be read
Yellow Partridge:Client FoodCo:Client Grace Chia:StaffMember Carlos Moncada:StaffMember Soong Motor Co:Client Advert Campaign Example: Links in instance/object diagram A link is a logical connection between two objects
Aggregation • In a plain association, the two classes are at the same level: no one more important than the other • Aggregation: a special form of association between a whole and its parts • Relates an assembly class to its component classes • Represents a “has-a” relationship, meaning that an object of the whole has objects of the part(s) • The assembly object propagates instructions to component objects (access and control through the assembly class) • Two possibilities: • Physical: a part cannot be in more than one ‘whole’ • Catalog: a part can be in more than one ‘whole’
Aggregation Examples Depicted by a diamond at the assembly end 1..* 1..* * 1..* Document Sentence Word * 4..6 Crew Astronaut 15 Person Team
Aggregation example: graphical interface Window 0..2 * TitleBar Pane ScrollBar Border 2 Close Button Title Arrow Indicator
Aggregation - Tree-like Notation Window 0..2 * TitleBar Pane ScrollBar Border 2 Close Button Title Arrow Indicator
Recursive Aggregation Aggregation can be: • Fixed: the number and types of the parts is fixed • Variable: the types of parts may vary, but the number of levels is fixed • Recursive: the number of levels, and hence parts, is unlimited * * Block Program Compound statement Simple statement
Aggregation • The meaning of this simple form of aggregation is entirely conceptual. The open diamond distinguishes the ‘whole’ from the ‘part’, no more, no less. • This means that simple aggregation does not change the meaning of navigation across the association between the whole and the parts, nor does it link the lifetimes of the whole and its parts. • Semantics can be very imprecise. • As a general rule, you can mark an association as an aggregation whenassemblyinstances owns or controls access to the component instances.
Advert Campaign 1 0..* Advert Campaign Example Unfilled diamond signifies aggregation
Composition • A form of physical aggregation with strong ownership and coincident lifetime of part with whole: • Multiplicity at assembly/aggregate end may not exceed 1 (i.e., the component is not shared) • Distinguished from regular aggregation by means of a filled diamond • If the aggregate is destroyed, then the parts are destroyed as well Window scrollbar 2 title 1 body 1 Slider Header Panel
Alternative Composition Notations Window scrollbar title body 2 1 1 Slider Header Panel Window Window 2 Slider 2 scrollbar : Slider scrollbar 1 Header 1 title : Header title 1 Panel 1 body : Panel body
Sample C++ implementations • In C++ class Window { public: Window() { scrollbar = new Slider[2]; title = new Header; body = new Panel; } ~Panel() { delete [] scrollbar; delete title; delete body; } private: class Slider * scrollbar; class Header * title; class Panel * body; }; class Window { private: class Slider scrollbar[2]; class Header title; class Panel body; };
Student Course 1..* 0..* Composition and Aggregation • Student registration example: • Clearly not composition • Students could be in several courses • If course is cancelled, students are not destroyed!
Advert Campaign 1 1..* Filled diamond signifies composition Composition and Aggregation (II) • Advert Campaign example • This is (probably) composition • Advert is part of one campaign at a time • If the campaign is cancelled, the advert is probably cancelled too.
Propagation • A mechanism, common in compositions, where an operation on 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 • In the example below, if line segments change in a polygon, then its surface area may change as a result • If the polygon is scaled up, then this is propagated to all its line segments
Attribute vs. Association: Printing System Attributes describe objects of a class, Associations are used to link objects together! (So what’s wrong above?)
Generalization/Specialization • Definition: a relationship which organizes classes based on their similarities and differences • Is implemented with inheritance in object-oriented languages (more in later sections on *proper* generalization) • Sometimes called an “is-a” relationship • Should mean (but not always the case in practice): • Objects of the child class may be used anywhere the parent may appear, but not the reverse • The child is substitutable for the parent • Is transitive across an arbitrary number of levels
Generalization/Specialization • A class may have zero, one or more parents • Root (base) class: a class with no parent and one or more children • Leaf class: a class that has no children • Simple inheritance: a class has exactly one parent • Multiple inheritance: a class with more than one parent (not supported by all programming languages) • For your own sanity, avoid this anyway. • Notation: a solid directed line with a large open arrowhead, pointing to the parent
Simple/Multiple Inheritance multiple inheritance multiple inheritance single inheritance
Subclasses • Inherit the attributes, operations, and associations of their superclass(es) • Must obey all semantic restrictions of their superclass(es) • Can override the implementation of an operation vehicle size speed water vehicle land vehicle wheels propeller
Ancestors/Descendants • Multiple generalization levels when multiple discriminators • The discriminator is a label that describes the criteria used in the specialization • The terms ancestor and descendant refer to generalization across multiple levels. • An instance of a class is simultaneously an instance (transitively) of all its ancestors
Animal typeOfFood habitat AquaticAnimal LandAnimal Carnivore Herbivore AquaticCarnivore AquaticHerbivore LandCarnivore LandHerbivore Using Multiple Inheritance • Avoid duplication of properties (attributes) • Increases complexity
Avoiding unnecessary generalizations • No differences in operations • Inappropriate hierarchy of • classes, which should be instances * Recording RecordingCategory hasCategory Improved class diagram, with a corresponding instance/object diagram * title description subcategory artist :RecordingCategory :RecordingCategory video audio subcategory subcategory subcategory subcategory subcategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory :RecordingCategory music video jazz classical blues rock :Recording :Recording Let it be 9th Symphony The Beatles Beethoven
Generalization Constraints Constraints can be used to describe the relationship between a class and its subclasses. The generalization can be: complete // all subclasses have been specified (no more are expected) incomplete // some subclasses have been specified but it is known that others exist disjoint // objects of the parent may have no more than one of the children as a type e.g. class Person can be specialized into disjoint classes Man and Woman. overlapping // objects of the parent may have more than one of the children as a type e.g. class Vehicle can be specialized into overlapping subclasses LanVehicle and WaterVehicle (an amphibious vehicle is both) disjoint and overlapping applies only to multiple inheritance.
Complete Specialization Person {complete} Male Person Female Person Person {complete} ellipses indicate that other specializations are known to exist but are not shown ... Male Person
Incomplete Specialization indicates that defined model elements are not shown Fruit ... Apple {incomplete} indicates that other elements are know to exist but have not been defined Macintosh Cox Golden Delicious
Have qualifications recorded • Can be client contact for campaign • Bonus based on campaigns they have worked on Creative • Qualifications are not recorded • Not associated with campaigns • Bonus not based on campaign profits Admin Advert Campaign Example • Two types of staff:
StaffMember {abstract} staffName staffNo staffStartDate calculate Bonus( ) assignNewStaffGrade( ) getStaffDetails( ) AdminStaff calculateBonus( ) CreativeStaff qualification calculateBonus( ) assignStaffContact( ) Using Inheritance
Astronaut conducts 1..* 1..* Experiment Mission_Specialist conducts 0..* 1..* Astronaut Experiment mission_specialist Meaning of Roles • Roles can be thought of as a shorthand form of specialization and can be changed as such if needed Astronaut Experiment Aldrin Shepherd Frogs Spawning Collins Armstrong Mission Specialist Crystal Formation
Abstract, Root, Leaf, and Polymorphic Elements • Abstract class: may not have any direct instance • The name of the class is in italics (same thing for abstract operations) • Or The property {abstract} is written below the class’s name • A class that may have instance(s) is a concrete class • Leaf class / operation: may have no children / redefinitions • The property {leaf} is written below the class’s name • The property {leaf} is written after a leaf operation • Root class: may have no parent • The property {root} is written below the class’s name • Polymorphic operation: contrary to leaf operations, may have several implementations in an inheritance hierarchy (default)