Class Design Overview

Class Design Overview
2
Objectives: Class Design
 Define the purpose of Class Design and
where in the lifecycle it is performed
 Identify additional classes and relationships
needed to support implementation of the
chosen architectural mechanisms
 Identify and analyze state transitions in
objects of state-controlled classes
 Refine relationships, operations, and
attributes
3
Class Design in Context
[Early
Elaboration
Iteration]
[Inception
Iteration (Optional)]
Define a Candidate
Architecture
Perform
Architectural
Synthesis
Analyze Behavior
Refine the
Architecture
Design
Components
Design the
Database
(Optional)
Class
Design Designer
4
Class Design Overview
Supplementary
Specifications
Class
Design
Project Specific
Guidelines
Design Classes
Design Model
Design Use-Case
Realization Analysis Use-Case
Realization
Analysis Classes
5
Class Design Steps
 Create Initial Design
Classes
 Define Operations
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case
Collisions
 Handle Nonfunctional
Requirements in General
 Checkpoints
6
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
7
Class Design Considerations
 Class stereotype
 Boundary
 Entity
 Control
 Applicable design patterns
 Architectural mechanisms
 Persistence
 Distribution
 etc.
8
A class should have a single well-focused purpose.
A class should do one thing and do it well!
How Many Classes Are Needed?
 Many, simple classes means that each class
 Encapsulates less of the overall system
intelligence
 Is more reusable
 Is easier to implement
 A few, complex classes means that each class
 Encapsulates a large portion of the overall
system intelligence
 Is less likely to be reusable
 Is more difficult to implement
9
Strategies for Designing Boundary Classes
 User interface (UI) boundary classes
 What user interface development tools will be used?
 How much of the interface can be created by the
development tool?
 External system interface boundary classes
 Usually model as subsystem
<<subsystem>>
MainForm
SubWindow
Button DropDownList
MainWindow
10
Strategies for Designing Entity Classes
 Entity objects are often passive and persistent
 Performance requirements may force some re-factoring
Analysis
FatClassLazyDataHelper
- rarelyUsedAttr1
- rarelyUsedAttr2
Design
FatClass
- privateAttr
+ getCommonlyUsedAttr1()
+ getCommonlyUsedAttr2()
+ getRarelyUsedAtt1()
+ getRarelyUsedAtt2()
FatClassDataHelper
- commonlyUsedAttr1
- commonlyUsedAttr2
1 0..1
FatClass
- privateAttr
- commonlyUsedAttr1
- commonlyUsedAttr2
- rarelyUsed1
- rarelyUsed2
<< Entity >>
11
Strategies for Designing Control Classes
 What happens to Control Classes?
 Are they really needed?
 Should they be split?
 How do you decide?
 Complexity
 Change probability
 Distribution and performance
 Transaction management
12
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
13
 Messages displayed in interaction diagrams
 Other implementation dependent functionality
 Manager functions
 Need for class copies
 Need to test for equality
Operations: Where Do You Find Them?
: ClassA
1 : //Perform Responsibility
: ClassB : ClassA
1 : performResponsibility (): result
: ClassB
14
Name and Describe the Operations
 Create appropriate operation names
 Indicate the outcome
 Use client perspective
 Are consistent across classes
 Define operation signatures
 operationName([direction]parameter : class,..) :
returnType
• Direction is in
(default), out
or inout
• Provide short description, including meaning
of all parameters
15
Guidelines: Designing Operation Signatures
 When designing operation signatures,
consider if parameters are:
 Passed by value or by reference
 Changed by the operation
 Optional
 Set to default values
 In valid parameter ranges
 The fewer the parameters, the better
 Pass objects instead of “data bits”
16
Public
operations
Protected
operations
Private
operations
Operation Visibility
 Visibility is used to enforce encapsulation
 May be public, protected, or private
17
How Is Visibility Noted?
 The following symbols are used to specify
export control:
 + Public access
 # Protected access
 - Private access
Class1
- privateAttribute
+ publicAttribute
# protectedAttribute
- privateOperation ()
+ publicOPeration ()
# protecteOperation ()
18
Scope
 Determines number of instances of the
attribute/operation
 Instance: one instance for each class instance
 Classifier: one instance for all class instances
 Classifier scope is denoted by underlining the
attribute/operation name
Class1
- classifierScopeAttr
- instanceScopeAttr
+ classifierScopeOp ()
+ instanceScopeOp ()
19
Example: Scope
Student
- name
- address
- nextAvailID : int
+ addSchedule ([in] theSchedule : Schedule, [in] forSemester : Semester)
+ getSchedule ([in] forSemester : Semester) : Schedule
+ hasPrerequisites ([in] forCourseOffering : CourseOffering) : boolean
# passed ([in] theCourseOffering : CourseOffering) : boolean
+ getNextAvailID () : int
- studentID
20
Example: Define Operations
Student
+ getTuition() : double
+ addSchedule ( [in] aSchedule : Schedule)
+ getSchedule ( [in] forSemester : Semester) : Schedule
+ deleteSchedule ( [in] forSemester : Semester)
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering) : boolean
# hasPassed ( [in] aCourseOffering : CourseOffering) : boolean
+ getNextAvailID() : int
+ getStudentID() : int
+ getName() : String
+ getAddress() : String
0..1
+ registrant 0..1
1
RegistrationController 0..*
+ submitSchedule()
+ saveSchedule()
+ getCourseOfferings() : CourseOfferingList
+ getCurrentSchedule ( [in] forStudent : Student, [in] forSemester : Semester) : Schedule
+ deleteCurrentSchedule()
+ new ( [in] forStudentID : String)
+ getStudent ( [in] anID : int) : Student
ICourseCatalogSystem
+ getCourseOfferings()
+ initialize()
<<Interface>>
21
 Create Initial Design Classes
 Define Operations
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
Class Design Steps
22
Define States
 Purpose
 Design how an object’s state affects its
behavior
 Develop state machines to model this behavior
 Things to consider:
 Which objects have significant state?
 How to determine an object’s possible states?
 How do state machines map to the rest of the
model?
23
What is a State Machine?
 A directed graph of states (nodes) connected by
transitions (directed arcs)
 Describes the life history of a reactive object
State State
Transition
Guard Condition
Event Activity
State1
Event(args)[guard condition]/activity
State2
24
Pseudo States
 Initial state
 The state entered when an
object is created
 Mandatory, can only have
one initial state
 Choice
 Dynamic evaluation of
subsequent guard conditions
 Only first segment has a
trigger
 Final state
 Indicates the object’s end
of life
 Optional, may have more
than one
State1
State2
Initial State
Choice
Final State
25
 Significant, dynamic attributes
 Existence and non-existence of certain links
Identify and Define the States
The maximum number of students per course offering is 10
numStudents < 10 numStudents > = 10
Link to Professor
exists
Link to Professor
doesn’t exist
Professor
CourseOffering
Open Closed
0..*
0..1 Assigned Unassigned
26
 Look at the class interface operations
Events: addProfessor,
removeProfessor
Identify the Events
CourseOffering
+ addProfessor()
+ removeProfessor()
0..*
0..1
Professor
27
Identify the Transitions
 For each state, determine what events cause
transitions to what states, including guard
conditions, when needed
 Transitions describe what happens in response
to the receipt of an event
CourseOffering
+ addProfessor()
+ removeProfessor()
0..*
0..1
Professor
Assigned
Unassigned
removeProfessor addProfessor
28
StateC
Exit/someAction
StateB
Do/anActivity
StateA
Add Activities
 Entry
 Executed when the
state is entered
 Do
 Ongoing execution
 Exit
 Executed when the
state is exited
Entry/anAction
29
Example: State Machine
addStudent / numStudents = numStudents + 1
Unassigned
Assigned
Full
Canceled
do/ Send cancellation notices
Committed
do/ Generate class roster
closeRegistration [ has Professor assigned ]
close
/ numStudents = 0
addProfessor
closeRegistration
removeStudent [numStudents >0]/ numStudents = numStudents - 1
cancel
removeProfessor
[ numStudents = 10 ]
close[ numStudents < 3 ]
closeRegistration[ numStudents >= 3 ]
close[ numStudents >= 3 ]
addStudent /
numStudents = numStudents + 1
cancel
removeStudent[ numStudents > 0] / numStudents = numStudents - 1
close
[ numStudents = 10 ] cancel
30
Example: State Machine with Nested States and History
superstate
substate
addStudent /
numStudents = numStudents + 1
Open
Unassigned
Assigned
H
add a professor
Closed
Canceled
do/ Send cancellation notices
Full
Committed
do/ Generate class roster
closeRegistration
close
remove a professor
close[ numStudents < 3 ]
[ numStudents = 10 ]
closeRegistration[ numStudents >= 3 ]
close[ numStudents >= 3 ]
closeRegistration [ has Professor assigned ]
close
/ numStudents = 0
removeStudent[ numStudents > 0] / numStudents = numStudents - 1
cancel
cancel
31
Which Objects Have Significant State?
 Objects whose role is clarified by state
transitions
 Complex use cases that are state-controlled
 It is not necessary to model objects such
as:
 Objects with straightforward mapping to
implementation
 Objects that are not state-controlled
 Objects with only one computational state
32
 Events may map to operations
 Methods should be updated with state-specific
information
 States are often represented using attributes
 This serves as input into the “Define Attributes” step
How Do State Machines Map to the Rest of the Model?
Open
CourseOffering
- numStudents
+ addStudent()
Closed
[numStudents>=10]
addStudent / numStudents = numStudents + 1
[numStudents<10]
33
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
34
Attributes: How Do You Find Them?
 Examine method descriptions
 Examine states
 Examine any information the class itself
needs to maintain
35
Attribute Representations
 Specify name, type, and optional default value
 attributeName : Type = Default
 Follow naming conventions of implementation
language and project
 Type should be an elementary data type in
implementation language
 Built-in data type, user-defined data type, or
user-defined class
 Specify visibility
 Public: +
 Private: -
 Protected: #
36
- name
- address
- nextAvailID : int
- studentID : int
- dateOfBirth : Date
Student
Example: Define Attributes
RegistrationController
0..1
ICourseCatalogSystem
<< interface >>
Schedule
CourseOffering
- number : String = “100”
- startTime : Time
- endTime : Time
- day : String
- /numStudents : int = ()
- semester : Semester
0..1
0..1
0..1
+ registrant
+ currentSchedule
0..*
0..2 0..4
0..*
+ alternateCourses
1
0..*
+ primaryCourses
37
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
38
 What Is a Dependency?
 A relationship between two objects
 Purpose
 Determine where structural relationships are
NOT required
 Things to look for :
 What causes the supplier to be visible to the
client
Define Dependency
Client Supplier
39
Dependencies vs. Associations
 Associations are structural
relationships
 Dependencies are nonstructural
relationships
 In order for objects to “know
each other” they must be visible
 Local variable reference
 Parameter reference
 Global reference
 Field reference Association
Dependency
Supplier2
Client
Supplier1
40
Associations vs. Dependencies in Collaborations
 An instance of an association is a link
 All links become associations unless they have
global, local, or parameter visibility
 Relationships are context-dependent
 Dependencies are transient links with:
 A limited duration
 A context-independent relationship
 A summary relationship
A dependency is a secondary type of relationship in that it doesn't tell
you much about the relationship. For details you need to consult the
collaborations.
41
Local Variable Visibility
 The op1() operation contains a local
variable of type ClassB
ClassA
+ op1 ( )
ClassB
42
Parameter Visibility
 The ClassB instance is passed to the
ClassA instance
ClassA
+ op1 ( [in] aParam : ClassB )
ClassB
43
Global Visibility
 The ClassUtility instance is visible because
it is global
ClassA
+ op1 ( )
ClassB
+ utilityOp ( )
44
 Permanent relationships — Association (field visibility)
 Transient relationships — Dependency
 Multiple objects share the same instance
• Pass instance as a parameter (parameter visibility)
• Make instance a managed global (global visibility)
 Multiple objects don’t share the same instance (local
visibility)
 How long does it take to create/destroy?
 Expensive? Use field, parameter, or global visibility
 Strive for the lightest relationships possible
Identifying Dependencies: Considerations
45
Example: Define Dependencies (before)
<<interface>>
ICourseCatalogSystem
+ getCourseOfferings ( [in] forSemester : Semester) : CourseOfferingList
Student
- name
- address
- StudentID : int
+ addSchedule ( [in] aSchedule : Schedule )
+ getSchedule ( [in] forSemester : Semester ) : Schedule
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering ) : boolean
# passed ( [in] aCourseOffering : CourseOffering ) : boolean
RegistrationController
+ // submit schedule ()
+ // save schedule ()
+ // create schedule with offerings ()
+ // get course offerings ()
0..1
0..1 + registrant
0..* 1
+ courseCatalog
Schedule
- semester : Semester
+ submit ()
+ //save ()
# any conflicts? ()
+ //create with offerings()
0..*
1
0..1
0..1
+ currentSchedule
CourseOffering
- number : String = "100"
- startTime : Time
- endTime : Time
- day : String
+ addStudent ( [in] aStudentSchedule : Schedule)
+ removeStudent ( [in] aStudentSchedule : Schedule)
+ new ()
+ setData ()
0..*
0..4
+ primaryCourses
0..*
0..2
alternateCourses
46
Example: Define Dependencies (after)
<<interface>>
ICourseCatalogSystem
+ getCourseOfferings ( [in] forSemester : Semester) : CourseOfferingList
RegistrationController
+ // submit schedule ()
+ // save schedule ()
+ // create schedule with offerings ()
+ // get course offerings ()
0..1
+ registrant
Schedule
- semester : Semester
+ submit ()
+ //save ()
# any conflicts? ()
+ //create with offerings()
0..*
0..1
0..1
+ currentSchedule
CourseOffering
- number : String = "100"
- startTime : Time
- endTime : Time
- day : String
+ addStudent ( [in] aStudentSchedule : Schedule)
+ removeStudent ( [in] aStudentSchedule : Schedule)
+ new ()
+ setData ()
0..4
0..*
0..2
alternateCourses
Global visibility
Parameter visibility
Field visibility Field
visibility
Student
- name
- address
- StudentID : int
+ addSchedule ( [in] aSchedule : Schedule )
+ getSchedule ( [in] forSemester : Semester ) : Schedule
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering ) : boolean
# passed ( [in] aCourseOffering : CourseOffering ) : boolean
0..1 1
0..*
+ primaryCourses
47
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
48
Define Associations
 Purpose
 Refine remaining associations
 Things to look for :
 Association vs. Aggregation
 Aggregation vs. Composition
 Attribute vs. Association
 Navigability
 Association class design
 Multiplicity design
49
What Is Composition?
 A form of aggregation with strong
ownership and coincident lifetimes
 The parts cannot survive the whole/aggregate
Whole
Composition
Part
Whole Part
50
 Shared Aggregation
 Non-shared Aggregation
Aggregation: Shared vs. Non-shared
By definition, composition is non-shared aggregation.
Whole 1..* 0..* Part
Multiplicity > 1
Multiplicity = 1 Multiplicity = 1
Whole 1 0..* Part Whole 1 0..* Part
Composition
51
Aggregation or Composition?
 Consideration
 Lifetimes of Class1 and Class2
Aggregation
Composition
Class1 Class2
Class1 Class2
52
Example: Composition
1
0..*
Student Schedule
RegisterForCoursesForm 1
1
RegistrationController
53
Attributes vs. Composition
 Use composition when
 Properties need independent identities
 Properties have a complex structure and
properties of their own
 Properties have complex behavior of their own
 Properties have relationships of their own
 Otherwise use attributes
54
Example: Attributes vs. Composition
Composition of
separate class
Attribute
Student
- name
- address
- nextAvailID : int
- StudentID : int
- dateofBirth : Date
+ addSchedule ()
+ getSchedule ()
+ delete Schedule ()
+ hasPrerequisites ()
# hasPassed ()
Schedule
+ submit ()
+ //save ()
# any conflicts? ()
+ //create with offerings ()
+ new ()
+ passed ()
- semester : Semester
0..*
1
55
Review: What Is Navigability?
 Indicates that it is possible to navigate from
an associating class to the target class
using the association
RegistrationController
<<Control>>
Schedule CourseOffering
56
Navigability: Which Directions Are Really Needed?
 Explore interaction diagrams
 Even when both directions seem required, one
may work
 Navigability in one direction is infrequent
 Number of instances of one class is small
?
0..* 0..4
Schedule + primaryCourses CourseOffering
0..* 0..4
Schedule + primaryCourses CourseOffering
0..* 0..4
Schedule + primaryCourses CourseOffering
57
Example: Navigability Refinement
 Total number of Schedules is
small, or
 Never need a list of the
Schedules on which the
CourseOffering appears
 Total number of
CourseOfferings is small, or
 Never need a list of
CourseOfferings on a
Schedule
 Total number of
CourseOfferings and
Schedules are not small
 Must be able to navigate in
both directions
0..* 0..4
Schedule + primaryCourses CourseOffering
0..* 0..4
Schedule + primaryCourses CourseOffering
0..* 0..4
Schedule + primaryCourses CourseOffering
58
Association Class
 A class is
“attached” to an
association
 Contains
properties of a
relationship
 Has one
instance per link
<<entity>>
ScheduleOfferingInfo
- status
+ // is selected ()
+ // mark as selected ()
+ // mark as cancelled ()
Schedule CourseOffering
0..* + primaryCourses 0..4
0..* + alternateCourses 0..2
PrimaryScheduleOfferingInfo
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
<<entity>>
59
Example: Association Class Design
Design Decisions
0..* + primaryCourses 0..4
0..* + alternateCourses 0..2
PrimaryScheduleOfferingInfo
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
Schedule CourseOffering
Schedule CourseOffering
1
- theCourseOffering 0..*
0..* + alternateCourses 0..2
PrimaryScheduleOfferingInfo
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
- primaryCourseOfferingInfo
0..4
1
60
 Multiplicity = 1, or Multiplicity = 0..1
 May be implemented directly as a simple
value or pointer
 No further “design” is required
 Multiplicity > 1
 Cannot use a simple value or pointer
 Further “design” may be required
Multiplicity Design
Needs a
container for
CourseOfferings
Professor 0..1 0..* CourseOffering
+ Instructor
Professor 0..1 0..* CourseOffering
+ Instructor
61
Multiplicity Design Options
Explicit Modeling of a Container Class Detail Container via Note
Professor 0..1 0..* CourseOffering
+ Instructor
Professor 0..1 0..* CourseOfferingList
+ Instructor
CourseOffering Professor 0..1 0..*
+ Instructor
CourseOffering
List
62
Multiplicity Design: Optionality
 If a link is optional, make sure to include an
operation to test for the existence of the link
Professor CourseOffering
+ isTeaching () : boolean
0..1
0..* + hasProfessor () : boolean
63
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
Class Design Steps
64
What is Internal Structure?
 The interconnected parts and connectors
that compose the contents of a structured
class.
 It contains parts or roles that form its structure
and realize its behavior.
 Connectors model the communication link
between interconnected parts.
The interfaces describe what a class must do; its internal
structure describes how the work is accomplished.
65
Review: What Is a Structured Class?
 A structured class contains parts or roles
that form its structure and realize its
behavior
 Describes the internal implementation structure
 The parts themselves may also be
structured classes
 Allows hierarchical structure to permit a clear
expression of multilevel models.
 A connector is used to represent an
association in a particular context
 Represents communications paths among parts
66
What Is a Connector?
 A connector models the communication link
between interconnected parts. For
example:
 Assembly connectors
• Reside between two elements (parts or ports)
in the internal implementation specification of
a structured class.
 Delegation connectors
• Reside between an external (relay) port and
an internal part in the internal implementation
specification of a structured class.
67
Review: What Is a Port?
 A port is a structural feature that
encapsulates the interaction between the
contents of a class and its environment.
 Port behavior is specified by its provided and
required interfaces
 They permit the internal structure to be
modified without affecting external clients
 External clients have no visibility to internals
 A class may have a number of ports
 Each port has a set of provided and required
interfaces
68
Review: Port Types
 Ports can have different implementation
types
 Service Port - Is only used for the internal
implementation of the class
 Behavior Port - Requests on the port are
implemented directly by the class
 Delegation Port – Requests on the port are
transmitted to internal parts for implementation
69
Review: Structure Diagram With Ports
StructuredClassName
: PartA : PartB
Behavior Port
Delegation
Port
Service Port
Assembly Connector
Delegation Connector
70
Review: Structure Diagram
Course Registration System
:
StudentManagementSystem
:
: BillingSystem CourseCatalogSystem
billingSys
studentMgmtSys studentMgmtSys
courseCatalogSys
71
Example: Structure Diagram Detailed
StudentManagementSystem
:
MainStudentForm
:
RegistrationController
billingSys courseCatalogSys
regController
mainStudentForm
Mixed interfaces for communication with
BillingSystem and CourseCatalogSystem
billingSys courseCatalogSys
72
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
Class Design Steps
Light
73
Review: Generalization
 One class shares
the structure and/or
behavior of one or
more classes
 “Is a kind of”
relationship
 In Analysis, use
sparingly
Superclass
(Parent)
(Ancestor)
Generalization
Relationship
Subclasses
(Child)
(Descendants)
Account
+ balance
+ name
+ number
+ withdraw ()
+ createStatement ()
Checking Savings
+ getInterest ()
74
There are no direct instances of Animal
Lion Tiger
Animal
+ communicate ()
+ communicate () + communicate ()
Abstract and Concrete Classes
 Abstract classes cannot have any objects
 Concrete classes can have objects
All objects are either lions or tigers
Abstract class
Abstract operation
Communication
Discriminator
75
Name clashes on
attributes or operations Repeated inheritance
Multiple Inheritance: Problems
Resolution of these problems is implementation-dependent.
SomeClass
Bird
Animal
+ color
+ getColor ()
FlyingThing
+ color
+ getColor ()
Bird
Animal
+ color
+ getColor ()
FlyingThing
+ color
+ getColor ()
76
Generalization Constraints
 Complete
 End of the inheritance tree
 Incomplete
 Inheritance tree may be extended
 Disjoint
 Subclasses mutually exclusive
 Doesn’t support multiple inheritance
 Overlapping
 Subclasses are not mutually exclusive
 Supports multiple inheritance
77
Example: Generalization Constraints
Asset
Bank Account Real Estate Security
Savings Checking Stock Bond
{disjoint}
{disjoint,complete} {disjoint}
End of inheritance hierarchy
Multiple
Inheritance
not supported
78
Example: Generalization Constraints (continued)
Vehicle
AmphibiousVehicle
LandVehicle WaterVehicle
{overlapping}
Multiple
inheritance
supported
79
Is this correct?
Generalization vs. Aggregation
 Generalization and aggregation are often
confused
 Generalization represents an “is a” or “kind-of”
relationship
 Aggregation represents a “part-of” relationship
Window
WindowWithScrollbar
Scrollbar
80
Window
WindowWithScrollbar
Scrollbar
Generalization vs. Aggregation
Scrollbar
Window
WindowWithScrollbar
1
1
A WindowWithScrollbar “is a” Window
A WindowWithScrollbar “contains a” Scrollbar
81
Do these classes follow the “is a” style of programming?
Generalization: Share Common Properties and Behavior
 Follows the “is a” style of programming
 Class substitutability
List
+ insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Stack
Lion Tiger
Animal
+ communicate ()
+ communicate () + communicate ()
82
Generalization: Share Common Properties and Behavior (cont.)
List
+ insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Stack
Lion Tiger
Animal
+ communicate ()
+ communicate () + communicate ()
83
Generalization: Share Implementation: Factoring
 Supports the reuse of the implementation of
another class
 Cannot be used if the class you want to
“reuse” cannot be changed
List
+ insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Stack
SequentialContainer
List
+ insertTop ([in] item)
+ removeTop ()
Stack
+ insertBottom ([in] item)
+ removeBottom ()
+ insert ([in] item, [in] position)
84
Generalization Alternative: Share Implementation: Delegation
 Supports the reuse of the implementation of
another class
 Can be used if the class you want to “reuse”
cannot be changed
List
+ insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Stack List
Stack
+ insertBottom ([in] item)
+ removeBottom ()
+ insert ([in] item, [in] position)
1
1
85
Manufacturer A
Manufacturer B Manufacturer C
OO Principle:
Encapsulation
Review: What Is Polymorphism?
 The ability to hide many different
implementations behind a single interface
Remote Control
86
Generalization: Implement Polymorphism
Without Polymorphism
if animal = “Lion” then
Lion communicate
else if animal = “Tiger” then
Tiger communicate
end
With Polymorphism
Animal communicate
Lion Tiger
Animal
+ communicate ()
+ communicate () + communicate ()
87
Polymorphism: Use of Interfaces vs. Generalization
 Interfaces support implementation-independent
representation of polymorphism
 Realization relationships can cross generalization
hierarchies
 Interfaces are pure specifications, no behavior
 Abstract base class may define attributes and
associations
 Interfaces are totally independent of inheritance
 Generalization is used to re-use implementations
 Interfaces are used to re-use behavioral specifications
 Generalization provides a way to implement
polymorphism
88
Polymorphism via Generalization Design Decisions
 Provide interface only to descendant classes?
 Design ancestor as an abstract class
 All methods are provided by descendent classes
 Provide interface and default behavior to
descendent classes?
 Design ancestor as a concrete class with a default
method
 Allow polymorphic operations
 Provide interface and mandatory behavior to
descendent classes?
 Design ancestor as a concrete class
 Do not allow polymorphic operations
89
Metamorphosis exists in the real world.
How should it be modeled?
What Is Metamorphosis?
 Metamorphosis
 1. A change in form, structure, or function;
specifically the physical change undergone by
some animals, as of the tadpole to the frog.
 2. Any marked change, as in character,
appearance, or condition.
~ Webster’s New World Dictionary, Simon &
Schuster, Inc.
90
Example: Metamorphosis
 In the university, there are full-time students and
part-time students
 Part-time students may take a maximum of three
courses but there is no maximum for full-time students
 Full-time students have an expected graduation date
but part-time students do not
FullTimeStudent
+ name
+ address
+ studentID
+ gradDate
PartTimeStudent
+ name
+ address
+ maxNumCourses
+ studentID
91
What happens if a
part-time student
becomes a full-time
student?
Modeling Metamorphosis: One Approach
 A generalization relationship may be created
FullTimeStudent
Student
+ name
+ address
+ studentID
+ gradDate
PartTimeStudent
+ maxNumCourses
92
 Inheritance may be used to model common
structure, behavior, and/or relationships to
the “changing” parts
Modeling Metamorphosis: Another Approach
Student
+ name
+ address
+ studentID
FullTimeStudent
+ gradDate
PartTimeStudent
+ maxNumCourses
FullTimeClassification
+ gradDate
PartTimeClassification
+ maxNumCourses
Student
+ name
+ address
+ studentID
Classification
1
1
+ changeToFullTime
93
Modeling Metamorphosis: Another Approach (continued)
 Metamorphosis is accomplished by the object
“talking” to the changing parts
: Student
: FullTimeClassification
: StudentManager : PartTimeClassification
2 : delete
3 : create
1 : changeToFullTime
X
94
Metamorphosis and Flexibility
 This technique also adds to the flexibility of the
model
ResidentInformation
1
+ dorm 0..1
+ room
+ roomKeyID
FullTimeClassification
+ gradDate
PartTimeClassification
+ maxNumCourses
Student
+ name
+ address
+ studentID
Classification 1
1
+ changeToFullTime
95
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
96
Resolve Use-Case Collisions
 Multiple use cases may simultaneously access
design objects
 Options
 Use synchronous messaging => first-come firstserve
order processing
 Identify operations (or code) to protect
 Apply access control mechanisms
• Message queuing
• Semaphores (or “tokens”)
• Other locking mechanism
 Resolution is highly dependent on implementation
environment
97
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
98
Handle Non-Functional Requirements in General
Analysis Class
Analysis Mechanism(s)
Student
Schedule
CourseOffering
Course
RegistrationController
Persistency, Security
Persistency, Legacy Interface
Persistency, Legacy Interface
Distribution
Persistency, Security
Design
Guidelines
Remote Method
Invocation (RMI)
Persistency
Analysis
Mechanism
(Conceptual)
Design
Mechanism
(Concrete)
Implementation
Mechanism
(Actual)
OODBMS
RDBMS
JDBC
ObjectStore
Java 1.5 from Sun
Legacy
Data
New
Data
Distribution
Persistency
SomeDesignClass
99
Class Design Steps
 Create Initial Design Classes
 Define Operations
 Define Methods
 Define States
 Define Attributes
 Define Dependencies
 Define Associations
 Define Internal Structure
 Define Generalizations
 Resolve Use-Case Collisions
 Handle Non-Functional Requirements in General
 Checkpoints
100
Checkpoints: Classes
 Clear class names
 One well-defined abstraction
 Functionally coupled attributes/behavior
 Generalizations were made
 All class requirements were addressed
 Demands are consistent with state machines
 Complete class instance life cycle is described
 The class has the required behavior
101
Checkpoints: Operations
 Operations are easily understood
 State description is correct
 Required behavior is offered
 Parameters are defined correctly
 Messages are completely assigned operations
 Implementation specifications are correct
 Signatures conform to standards
 All operations are needed by Use-Case
Realizations
102
Checkpoints: Attributes
 A single concept
 Descriptive names
 All attributes are needed by Use-
Case Realizations
103
Checkpoints: Relationships
 Descriptive role names
 Correct multiplicities 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值