UML Class Diagram

60,707 views

Published on

Course on object-oriented system modeling with UML class diagrams

Published in: Education, Technology
7 Comments
34 Likes
Statistics
Notes
No Downloads
Views
Total views
60,707
On SlideShare
0
From Embeds
0
Number of Embeds
3,736
Actions
Shares
0
Downloads
2,032
Comments
7
Likes
34
Embeds 0
No embeds

No notes for slide

UML Class Diagram

  1. 1. Session 2: Specifying System Structure using UML Class Diagrams Analysis and Specification of Information Systems Spring 2008 Eran Toch http://www.technion.ac.il/~erant Specification and Analysis of Information Systems Spring 2005 1
  2. 2. Outline • Introduction • Classes, attributes and operations • Relations • Generalization • Guidelines for effective class modeling All images are under Creative Commons license 2
  3. 3. System Development Process Phase Actions Outcome Business Initiation Raising a business need documents Interviewing stakeholders, exploring the Organized Analysis system environment documentation Analyze the engineering aspect of the Logical System Specification system, building system concepts Model Program, build, unit-testing, integrate, Testable Implementation documentation system Testing & Integrate all components, verification, Testing results, Integration validation, installation, guidance Working sys System Maintenance Bug fixes, modifications, adaptation versions Intro | Classes | Relations | Generalization | Guidelines 3
  4. 4. Logical System Models • Logical system models depict what a system is or what a system must do—not how the system will be implemented. • The model may contain: – Data models (e.g., class diagram) – Process models (e.g., sequence diagram) – User interaction models (e.g., use case) • They depict it using a modeling language – Formal (or partially formal) – Understandable (visual or textual) Intro | Classes | Relations | Generalization | Guidelines 4
  5. 5. Elements of Modelling Language • Symbols: Standard set of symbols C • Syntax: Acceptable ways of combining symbols C C • Semantics: Meaning given to language C2 expressions C1 C1 sends a message to C2 Intro | Classes | Relations | Generalization | Guidelines 5
  6. 6. Advanced Properties • Expressiveness: What the OK: C1 sends messages to C2 language can say Not OK: C1 sends messages to C2, after all messages of C2 were recieved • Methodology: Procedures to be followed 1. Model all classes 2. Model all relations 3. Model all inheritance • Guidelines: Suggestions Try to model classes with a on how to build effective balanced number of associations models Intro | Classes | Relations | Generalization | Guidelines 6
  7. 7. Modeling Approaches Modeling approaches differ from each other according to their view of the world Structural Models Behavior Models Focused on describing the Focused on the dynamics of structure of the system – the the system: how does it elements that are fixed and change over time. remain unchanged over time Intro | Classes | Relations | Generalization | Guidelines 7
  8. 8. Example: from Architecture Architect Louis Isadore Kahn 1901-1074 8
  9. 9. Structural Architecture Model (Plans for Philadelphia‘s City Center(1953 9
  10. 10. Behavior Modeling Models of Philadelphia‘s Traffic Behavior (1953) 10
  11. 11. Outline • Introduction • Classes, attributes and operations • Relations • Generalization • Guidelines for effective class modeling 11
  12. 12. Object-Oriented Approach • Objects are abstractions of real-world or system entities Reality Domain Model Domain bus models vehicle car models cup models Intro | Classes | Relations | Generalization | Guidelines 12
  13. 13. Classes A class is a template Produt for actual, in-memory, serialNumber instances name price Class Name buy() display() Attributes Operations Intro | Classes | Relations | Generalization | Guidelines 13
  14. 14. Attributes - Signature [visibility] name [[multiplicity]] [: type] [=initial value] [{property}] • visibility: the access rights to the attribute - multiplicity: how many instances of the attribute are they: - middleName [0..1] : String, phoneNumber [1..*] - Type: the type of the attribute (integer, String, Person, Course) - initial value: a default value of the attribute - salary : Real = 10000, position : Point = (0,0) - property: predefined properties of the attribute - Changeable, readOnly, addOnly, frozen (C++: const, Java: final) Intro | Classes | Relations | Generalization | Guidelines 14
  15. 15. Attributes - Examples + isLightOn : boolean = false - numOfPeople : int mySport + passengers : Customer[0..10] - id : long {readOnly} Intro | Classes | Relations | Generalization | Guidelines 15
  16. 16. Operations - Signature [visibility] name [(parameter-list)] [: return-type] [{property}] • An operation can have zero or more parameters, each has the syntax: – [direction] name : type [=default-value] – Direction can be: in (input paremter - can’t be modified), out (output parameter - may be modified), inout (both, may be modified) • Property: – {leaf} – concrete operation – {abstract} – cannot be called directly – {isQuery} – operation leaves the state of the operation unchanged – … Intro | Classes | Relations | Generalization | Objects | Guidelines 16
  17. 17. Operations - Examples What’s the + isLightOn() : boolean difference? + addColor(newColor : Color) + addColor(newColor : Color) : void # convertToPoint(x : int, y : int) : Point - changeItem([in] key : string, [out] newItem : Item) : int Intro | Classes | Relations | Generalization | Guidelines 17
  18. 18. Visibility • public (+) – external objects can access the member • private (-) – only internal methods can access the member • protected (#) – only internal methods, or methods of specialized objects can access the member Produt We will try to keep the visibility as minimal as - serialNumber possible - name # price + buy() + display() - swap(x:int,y: int) Intro | Classes | Relations | Generalization | Guidelines 18
  19. 19. Full Blown Class <<abstract>> Window {transient Stereotype status=tested} Constraints +size:Area = (100,100) #visibility:Boolean = invisible +default-size:Rectangle #maximum-size:Rectangle -xptr: XWindow +display () +hide () +create () -attachXWindow(xwin:Xwindow*) Intro | Classes | Relations | Generalization | Guidelines 19
  20. 20. Object Diagram • In an Object Diagram, class instances can be modeled Produt Apple Ipod : Product serialNumber name Apple IMac : Product price In runtime name = “IMac 1C” buy() price = 1456 $ display() serialNumber = 184934 Sony Vaio : Product name = “Vaio Portable” price = 2999 $ serialNumber = 113234 Class Diagram Object Diagram Intro | Classes | Relations | Generalization | Guidelines 20
  21. 21. Outline • Introduction • Classes, attributes and operations • Relations • Generalization • Guidelines for effective class modeling 21
  22. 22. Intro | Classes | Relations | Generalization | Guidelines 22
  23. 23. Relations • A relation is a template for a connection between two instances. • Relations are organized in a Hierarchy: – Dependency: indicate runtime relation Dependency between classes – Associations: consistent relations – Composition: whole-part Association relations Composition Aggregation Intro | Classes | Relations | Generalization | Guidelines 23
  24. 24. Associations Produt Order serialNumber orderID name * * date price includes checkout() buy() addProduct(Product p) display() clearAll() Name + reading Multiplicity direction Indicates cardinality • – 1:1default • Objects on both sides of the •3 – exactly 3 object association can find each other •* (or n) - unbounded •1..* - 1 to eternity • The relation is consistent in •3..9 – 3 to 9 time (unless removed) Intro | Classes | Relations | Generalization | Guidelines 24
  25. 25. Navigation Folder File Why is it directional? For example, if we want to know the files of each folder. However, we do not have a requirement for knowing the folder of each file. • If an association is directed, messages can pass only on that direction • If the association does not have directions, then it’s defined as a bidirectional association, and messages can pass in both directions • By default, all relations should be directed, unless the requirements dictate a bidirectional relation Intro | Classes | Relations | Generalization | Guidelines 25
  26. 26. Association Classes Denoted as a class attached to the association, and specify properties of the association Produt Order serialNumber orderID name * * date price checkout() buy() addProduct(Product p) display() clearAll() OrderLine According to the An association class is requirements, each numberOfProducts : int a “normal” class, and giftWrap : boolean product can appear is may include relations, addAnother() several orders, and each inheritance etc. removeOne() order may include several products Intro | Classes | Relations | Generalization | Guidelines 26
  27. 27. Association Class - Objects Links should be verified, according to the association multiplicity For each link, an association class instance should be declared Intro | Classes | Relations | Generalization | Guidelines 27
  28. 28. Relations & Attributes What is the problem here? • Relations are denoted with associations, not attributes. • Implementation (pointers, arrays, vectors, ids etc) is left to the detailed design phase. Intro | Classes | Relations | Generalization | Guidelines 28
  29. 29. Role Names • Names may be added at each end of the association • Provide better understanding of the association meaning • Especially helpful in self-associated classes Worker * 1..* * Person Company employee employer 0..1 Manages Manager Intro | Classes | Relations | Generalization | Guidelines 29
  30. 30. Ternary Associations Employee empNum : integer * Project WorkingDay ID:integer * * theDate : Date ProjectAttendance hours : double workDescription : String Intro | Classes | Relations | Generalization | Guidelines 30
  31. 31. Qualifiers • A qualifier is an attribute or list of attributes whose values serve to partition the set of objects associated with an object across an association College Chessboard Student ID rank : int 1..* file : int Qualifier 1 1 1 Student Square • The qualifier limits the multiplicity of the target object according to the qualifier attribute. Thus, even though a Bank has many persons, it has one or zero person with a particular account # Intro | Classes | Relations | Generalization | Guidelines 31
  32. 32. Constraints • Constrains are simple properties of associations, classes and many other things in UML • Specify limitations that implementers need to satisfy Window length Property width Constraints {0.8 ≤length/width≤1.5} 1 {ordered} Denotes Dictionary Language Word explicit order * of instance Intro | Classes | Relations | Generalization | Guidelines 32
  33. 33. Constraints - cont‘d A full order on associated objects Project {ordered} Outsource * * Task {xor} Committee memberOf * {subset} chairOf * boss Only one of the Employee 0..1 associations can exist for a salary given instance (what is the * meaning of “or”?) {salary < boss.salary} Intro | Classes | Relations | Generalization | Guidelines 33
  34. 34. Constraints • Constraints can be applied to almost every element in UML diagrams, using: – natural language – mathematical notation – OCL (Object Constraint Language) • Expressing: – Invariants: interest > 3% – Preconditions: before loan() takes place, salary > 5,000$ – Postconditions: after loan() takes place, dayCollect = 1 or 10 See http://www.klasse.nl/ocl/index.html Intro | Classes | Relations | Generalization | Guidelines 34
  35. 35. Intro | Classes | Relations | Generalization | Guidelines 35
  36. 36. Dependency • Notated by a dotted line • The most general relation between classes • Indicates that an object affects another object Accounting SecurityControl System <<creates>> <<modifies>> AccountingSystem creates a Receipt object Reciept Order Intro | Classes | Relations | Generalization | Guidelines 36
  37. 37. Dependency – cont‘d • Dependencies are the most abstract type of relations. • Properties: – Dependencies are always directed (If a given class depends on another, it does not mean the other way around). – Dependencies do not have cardinality. • If instances of two classes send messages to each other, but are not tied to each other, then dependency is appropriated. • Types: – «call» – «create» Intro | Classes | Relations | Generalization | Guidelines 37
  38. 38. Aggregation • “Whole-part” relationship between classes • Assemble a class from other classes – Combined with “many” - assemble a class from a couple of instances of that class Word Processing Document Author fileName Permission * * * Picture Folder name Intro | Classes | Relations | Generalization | Objects | Guidelines 38
  39. 39. Composition • Composition is a stronger form of aggregation • Contained objects that live and die with the container • Container creates and destroys the contained objects Window Operating close() System move() 0..2 1 Slider Header Panel Intro | Classes | Relations | Generalization | Objects | Guidelines 39
  40. 40. Composition vs. Aggregation Aggregation Composition Part can be shared by several Part is always a part of a single wholes whole 0..4 * * category document Window Frame Parts can live independently Parts exist only as part of the (i.e., whole cardinality can be whole. When the wall is 0..*) destroyed, they are destroyed Whole is not solely responsible Whole is responsible and for the object should create/destroy the objects Intro | Classes | Relations | Generalization | Objects | Guidelines 40
  41. 41. Outline • Introduction • Classes, attributes and operations • Relations • Generalization • Guidelines for effective class modeling 41
  42. 42. Generalization – Definitions • Super Class (Base class) – Provides common functionality and data members Super Class • Subclass (Derived class) – Inherits public and protected members from the super class … – Can extend or change behavior of super class by overriding methods • Overriding – Subclass may override the behavior Subclass of its super class Intro | Classes | Relations | Generalization | Guidelines 42
  43. 43. Intro | Classes | Relations | Generalization | Guidelines 43
  44. 44. Generalization – advantages • Modularity: GraphicComponent – Eliminate the details x : int y : int – Find common paint() characteristics among repaint() classes – Define hierarchies • Reuse: Button Image caption : String picture : File – Allow state and behavior press() paint() to be specialized ImageButton Overriding clickImage() Multiple Inheritance Intro | Classes | Relations | Generalization | Guidelines 44
  45. 45. Generalization Guidelines • Look carefully for similar properties between objects, sometimes they are not so obvious User Interface updateName(...) What’s the updateDesc(...) problem here? Document Product Order Worker id : long id : long * id : long id : long name : String name : String *|includes name : String name : String desc : String desc : String desc : String desc : String subject : Subject availability : int date : Date Salary : Float workYears : int getCategory() : getCategory() : * Category Category Done by } * * * * * Category name : String importance : int Intro | Classes | Relations | Generalization | Guidelines 45
  46. 46. Generalization – cont‘d Resource ID and name User Interface are common id : long name : String updateName(...) updateDesc(...) to all classes desc : String Association is the same Order Worker Product Document as any date : Date Salary : Float availability : int subject : String other Done by } * * workYears : int date : Date attribute includes } * * CategorizedResource Category * * getCategory() : name : String Category importance : int Intro | Classes | Relations | Generalization | Guidelines 46
  47. 47. Abstract Class • A class that has no direct instances Denoted by an Content Italics name Or by the stereotype <<abstract>> “abstract” Article Picture 1..* has picture News Magazine Article Article 1..* Intro | Classes | Relations | Generalization | Guidelines 47
  48. 48. Models and Sets Intro | Classes | Relations | Generalization | Guidelines 48
  49. 49. Generalization and Sets GraphicComponent Instances x : int y : int paint() GraphicComponent repaint() Button Image Image caption : String picture : File Button press() paint() ImageButton ImageButton Class clickImage() Class Representation Set Representation Intro | Classes | Relations | Generalization | Guidelines 49
  50. 50. Interfaces • Interface encapsulates the internal behavior of a class and its signature. • It is actually, a contract, that each implementing class must honor. Implementation Interface External Object Operation 1 Operation 1 Impl’ Operation 1 Declaration Operation 1 Operation 1 Operation 2 Operation 2 impl’ Operation 2 Declaration Data Intro | Classes | Relations | Generalization | Guidelines 50
  51. 51. Interface Terminology Class1 «interface» ISomething method1() method2() Class2 Realization relation: Intro | Classes | Relations | Generalization | Guidelines 51
  52. 52. Example: Microsoft‘s Common Object Model 4 5 3 2 90 80 70 60 50 East 40 West 30 North 20 10 0 1st Qtr 2nd Qtr 3rd Qtr 4th Qtr ∑ Λν ∉ ℵ 2007 ‫מרץ‬ ‫מרץ‬ 2007 1 25 ‫א‬ 26 ‫ב‬ 27 ‫ג‬ 28 ‫ד‬ 1 ‫ה‬ 2 ‫ו‬ 3 ‫ש‬ 4 5 6 7 8 9 10 0..∞ 11 18 12 19 13 20 14 21 15 22 16 23 17 24 25 26 27 28 29 30 31 1 2 3 4 5 6 7 Intro | Classes | Relations | Generalization | Guidelines 52
  53. 53. Interfaces Notation «interface» ICommonObject Client Application uniqueID : ID width : int height : int create() move() delete() display() Realization: The object guarantees to carry out the Equation PowerPoint Excel Document Document contract specified by the interface Intro | Classes | Relations | Generalization | Guidelines 53
  54. 54. Interfaces Notations - cont‘d • Another way to notate interfaces: Provided Required Interface Equation ... Client ... ICommonObject Intro | Classes | Relations | Generalization | Guidelines 54
  55. 55. Outline • Introduction • Classes, attributes and operations • Relations • Generalization & Encapsulation • Guidelines for effective class modeling 55
  56. 56. Guidelines • How to model? – Methodologies for class specification • Class normalization • Course Assumptions 56
  57. 57. How to Model? Bottom-up Process Top-down Process Starting with throwing all Starting with an overview of classes on the page, and the system, and then splitting then combining them: classes Product Configuration Purchase Shipping Catalogue Customer Process details Category Charging Order process Product spec Search engine results Credit data Intro | Classes | Relations | Generalization | Guidelines 57
  58. 58. Top-Down Methodology Credit card Analyzing Scope Catalogue validator Identifying major classes Catalogue Order Customer Identifying properties Order id, state... changeState() Identifying methods ship() Refining and Order State normalizing classes id started, ended Order Business Generalizing classes id Order Reviewing : Order : Customer id = 18734 name = “cohen” 58
  59. 59. CRC Cards • CRC Cards: – Class, Responsibility, Collaboration Example Intro | Classes | Relations | Generalization | Guidelines 59
  60. 60. Normalization 60
  61. 61. Normal Forms in UML Classes • A naïve model may have a Book bad problem of coupling: systemNumber : long – Data is inter-related title : String author : String – It is difficult to manage data orderOfAuthor : int items individually category : String[] copyNumber : long • Normalization: holderName : String returnDate : Date – A collection of design location : String strategies courseId : String courseName : String – Ensures loosely coupled design Naïve Model • Origin: relational database – But, we do not have primary keys in Class diagram 61
  62. 62. First Normal Form All properties must have a final number of values Here, I should add a 1:n with Book an example of Book systemNumber : long n:n title : String systemNumber : long author : String title : String orderOfAuthor : int author : String * Category * category : String[] orderOfAuthor : int categorized copyNumber : long copyNumber : int name : String holderName : String holderName : String returnDate : Date returnDate : Date location : String location : String courseId : String courseId : String courseName : String courseName : String The number of categories for a book is unbounded 62
  63. 63. Second Normal Form All properties must depend on the whole class essence, and not just a part of it st Author is a 1 normalization Order Author orderOfAuthor : int 1..* Book name : String systemNumber : long title : String written by author : String * Category * orderOfAuthor : int categorized * Category copyNumber : int Book name : String * holderName : String systemNumber : long categorized name : String returnDate : Date * title : String location : String courseId : String courseId : String courseName : String courseName : String location : String 1..* Has Copy copyNumber : int holderName : String returnDate : Date location : String 63
  64. 64. Third Normal Form All properties must depend only on the class’s essence Order Order Author Author orderOfAuthor : int orderOfAuthor : int 1..* 1..* name : String name : String written by written by Category * * * Category name : String Book * Book categorized * name : String systemNumber : long * categorized systemNumber : long 1..* Copy title : String title : String courseId : String location : String Has copyNumber : int courseName : String holderName : String 1..* location : String returnDate : Date 1..* Has Copy Textbook of copyNumber : int Course holderName : String returnDate : Date courseId : String location : String courseName : String 64
  65. 65. Guidelines for Effective Classes • Identifying classes – Very similar to identifying data repositories in DFD. Identify data elements, and model them. – Plus, think of classes that handle processes. If operations are complicated enough, we might want to model them separately. – Plus, think of the actors. Are all their needs covered by existing operations? Intro | Classes | Relations | Generalization | Guidelines 65
  66. 66. General Assumptions • Access – Users can execute any public operation of the classes (except when using specialized stereotypes). • Lifespan – Objects (except transient objects) have an endless life span. – We don’t need to bother with their serialization. • Simplicity – No need for get/set. – No need for constructors / distracters . Intro | Classes | Relations | Generalization | Guidelines 66
  67. 67. Finding Objects • Objects can be found, browsed through and located without any aggregating class. That’s enough for Loan Service to access all instances of Book Intro | Classes | Relations | Generalization | Guidelines 67
  68. 68. Guidelines – Modeling Actors • A common mistake is to model actors as classes • Remember - – Actors interact with the system directly, they don’t need to be represented a priory – Sometimes, the system saves data about customers, but it does not mean that they do all their actions through this class Intro | Classes | Relations | Generalization | Guidelines 68
  69. 69. Summary  Introduction – Structural modeling  Classes – Attributes and operations  Relations – Associations, constraints – Dependencies, compositions  Generalization – Inheritance – Interfaces  Object Diagrams  Guidelines: – Methodology – Normalization 69

×