Class & Object Diagram © copyright 2001 SNU OOPSLA Lab. Contents What is a Class Class Notation What is a Object CRC Cards Class Modeling Technique What is a Relationship What is a class Class The most fundamental concepts of object-oriented design and programming are classes and objects State( or data, attribute ) Behavior( or function, operation ) Shape Class 명 Attribute 명 origin move ( ) resize ( ) display ( ) Class notation Operation 명 What is a class Class defines a collection of similar instances defines the interface and implementation of its instances It exists at compilation time and serves as a type Example 1. Business System Example 2. Technical System Customer, Agreement, Invoice, Debt, Asset, Quotation Sensor, Display, I/O card, Engine, Button, Control class Example 3. System Software File, Executable Program, Device, Icon, Window, Scrollbar Class Notation Class Attribute Operation Class Notation Class Name Each Class has a unique name Simple Name : Class itself Path Name : Class가 소속된 Package명을 포함 Name should be a noun Name should be derived from problem domain and should be as unambiguous as possible << Simple Name >> Temperature Sensor Customer Wall UML notation for a class << Path Name >> Business Rules :: FraudAgent Java :: awt :: Rectangle Class Notation Attribute describe the characteristics of the objects • property • type Attributes Wall Visibility Name : Type = Default Value Attribute Default Value Attribute Type Signature Attribute Name + : Public - : Private # : Protected + height : float + width : float + thickness : float + isLoadBearing : Boolean = false Customer + name + address + phone -birthdate UML notation for attributes Class Notation Operation Operations are used to manipulate the attributes or to perform other actions A operation is described with a return-type, a name, and zero or more parameters ( signature of the operation ) what class can do, what services it offers the interface to the class Visibility Name (Parameter-List) : Return-Type-Expression {Property-String} Class : Operation Object : Method Class Notation Operation FaudeAgent Operations Rectangle + add ( ) + grow ( ) - move ( ) + isEmpty ( ) TemperatureSensor reset ( ) setAlarm (t : Temperature) value ( ) : Temperature <<constructor>> new ( ) new (p : Policy) <<process>> process (o : Order) ... <<query>> isSuspect (o : Order) isFraudulent (o : Order) <<helper>> validateOrder (o : Order) Stereotype What is a Object Object A particular instance of a class Created as needed Represent several kinds of concepts Physical entity : automobile, credit card scanner Role : John Smith in the role of a customer Organization unit Interaction What is a Object Object An object must have three properties interface Identity : distinguish this object from all others( OID ) State : an object should maintain data about itself Behavior : an object should be able to perform actions request from other objects current Order hidden middle :Order current Order :Order request to other objects UML notation for Order objects CRC Cards Responsibility A high-level description of the purpose of the class How to do responsibility : Attributes and Operations CRC(Class Responsibility Collaboration) Card FraudAgent Order Class Check if items in stocks Responsibility Responsibilities -- determine the risk of a customer order -- handle customer - specific criteria for fraud Determine price Check for valid payment Dispatch to delivery address Order Line “ Customer Collaboration CRC Cards CRC (Class Responsibility Collaboration) Cards The responsibilities of a class are general statements about the operations of the class A class should normally have at most three or four responsibilities Collaborators are other classes which help a class to carry out its responsibilities If an object of one class collaborates with an object of another class, it does so by sending it a message CRC cards can be used to walk through use cases Class Modeling Technique A "good" class model has the following properties: It satisfies the current system requirements and was built quickly It enables the software system to be easy to maintain and to adapt to future requirements Class Naming The name of a class is particularly important. It should be meaningful and usually corresponds to a real-world thing or role Class Modeling Technique Two Object-Oriented Design Camps : Data Driven Design (DDD) Use the noun identification technique to identify all the data in the system Create classes containing related data Responsibility Driven Design (RDD) Identify all the responsibilities in the system Create classes with related responsibilities Uses CRC (Class, Responsibilities, Collaborations) cards Class Modeling Technique Finding Classes Do we have that should be stored or analyzed ? Do we have external system ? external system is modeled as class Do we have any patterns, class libraries, components, and so on ? Are there devices that the system must handle ? Do we have organizational parts ? Which roles do the actors in the business play ? Class Modeling Technique Noun Identification Technique Classes are usually derived from the following real-world items : Transaction actions commit ( ) rollBack ( ) wasSuccessful ( ) Tangible or "real-world" things: book, copy, course Roles: library member, student, director of studies Events: arrival, leaving, request (help find associations) Interactions: meeting, intersection Customer Shipment name address phone birthdate Responsibilities -- maintain the information regarding products shipped against an order -- track the status and location of the shipped product Product id name price location Class Modeling Technique Identifying Inappropriate Classes: redundant - the same class has different names. vague - you do not know what the noun means. an event or an operation - Does it have state, behavior and identity? meta-language - the noun is part of our language of modeling and not part of the problem domain. outside the scope of the system - the noun is relevant to describing how the system works, but does not refer to something in the system. an attribute - where a noun refers to something simple with no behavior. Special Class – Actors as Classes Actor : external agent interact with system, but are not a part of the system itself black box to the system : internal implementations are irrelevant UML treats actors as special stereotyped classes stereotyped class : like a normal class, but it has special semantics don’t have to implement it or understand its internal details <<actor>> Telephone Agent Telephone Agent The telephone agent actor class What is a Relationship Relationship Elements in class and object diagrams are not “islands” Relationship Type : Dependency, Generalization, Association Dependency Window Event open ( ) close ( ) move ( ) display ( ) handleEvent ( ) ConsoleWindow Generalization DialogBox Association Control Dependency Relationship Dependency Relationship A semantic connection between two model elements, one independent and one dependent model element A change in the independent element will affect the dependent element One class takes an object of another class as a parameter One class accesses a global object of another class Transaction name playOn (c:Channel) start ( ) stop ( ) reset ( ) Channel Dependency Relationship Generalization Relationship Generalization Relationship A taxonomic relationship between a more general element and a more specific element( In UML, element may be use case, class and package ) The more specific element is fully consistent with the more general element and contain additional information “ is-a” Relationship( a car is a vehicle; a sales-manager is an employee, etc ) Generalization is only used on types, never on instances( a class can inherit another class, but an object cannot inherit another object ) The attributes, operations and all associations are inherited from a superclass to a subclass Visibility : public(+), private(-), protected(#) Generalization Relationship Shape Generalized Relationship Rectangle corner : Point Square origin move ( ) resize ( ) display ( ) Base Class Circle Polygon radius : Float points : List display ( ) Leaf Class A class hierarchy for shape Association Relationship Association Relationship A connection between classes, a semantic connection(link) between objects of the classes involved in the association Bidirectional : both objects are aware of each other name name direction Works for Person Company Association Relationship 1..* Person Owns 0..* Owned by Represent multiplicity Car Association Relationship Association Relationship In general, class A and class B are associated if: an object of class A sends a message to an object of class B an object of class A creates an object of class B an object of class A has an attribute whose values are objects of B or collections of objects of class B an object of class A receives a message with an object of class B as an argument Every copy object (of class Copy) is associated by "is a copy of" with just one book (of class Book). Each book object may have any number of copies associated with it. Association Relationship A * * B wife Person Can be transformed into A * 1 B 1 husband * B A bidirectional many-to-many association can be transformed into two one-to-many association Car * company car drives * driver Person A person plays the role of a driver and a car plays the role of a company car Roles are the context in which objects act. married to Both husband and wife are people Association Relationship Insurance company 1 0..* Insurance contract Insurance contract 0..* 0..* 0..* {ordered} {or} 1..* Person 1..* 1..* Company Customer An or-association shows that only one of the associations is valid at a time An ordered association Aggregation Relationship Aggregation A special case of association “whole-part” relationship Navy A car that consists of four wheels, an engine, a chassis, a gear box, and so on “consists of”, “contains”, “is part of” * Warship The Navy contains many warships. The parts(the warships) compose the whole(the Navy) The hollow diamond shows the aggregation Aggregation Relationship Shared Aggregation The parts may be parts in any wholes Shared is shown by its multiplicity Team * * Members Person A team is composed of team members. One person could be a member of many teams. The people are shared parts Aggregation Relationship Composition Aggregation A composition aggregation owns its parts Strong ownership The parts “live” inside the whole The parts will be destroyed together with its whole Window * Text * Listbox * Button * Menu The diamond shows the composition aggregate; the window contains( is aggregated of ) many menus, buttons, and texts Relationship Modeling Technique Simple Dependency Modeling 특정 Class가 다른 Class를 Operation에서 Parameter로만 사용 하는 관계 Operation에서 Parameter로 상대 Class를 사용하려는 Class쪽에 서 의존 관계를 표현 CourseSchedule add (c : Course) remove (c : Course) Iterator Course Relationship Modeling Technique Single Inheritance Modeling 구조적, 행동적 특성을 파악하여 Generalization Class와 Specialization Class로 구분하여 작성 Class 집합에서 둘 이상 다수의 Class에 공통으로 존재하는 책임, 속성, Operation을 파악 파악된 책임, 속성, Operation을 일반화 Class로 작성 특수화 Class는 일반화 Class로부터 상속되도록 Security 관계를 설정 presentValue ( ) history ( ) CashAccount interestRate presentValue ( ) Stock Bond presentValue ( ) SmallCapStock presentValue ( ) LargeCapStock Property assesment presentValue ( ) Relationship Modeling Technique Associative Relationship Modeling 의존/일반화(부분 관계) 관계와 같이 일방적인 관계가 아닌 Class 간에 대등한 관계 한 쌍의 Class에 대하여 한 객체들로부터 다른 객체로의 왕래가 필요하면 두 Class사이에 연관 관계를 지정 한 쌍의 Class에 대하여 한 Class 객체가 다른 Class 객체와 Operation Parameter 이외의 방법으로 교류하면 관계 설정(행동 중심적 관점) 각 연관에 대해 다중성, 역할 명을 표현 한쪽 Class가 구조적, 조직적으로 전체가 되고 다른 쪽이 부분 관계와 같이 판단되면 집합 연관으로 표현 has 0 .. 1 School 1 .. * Department 1 1 .. * 1 .. * 1 .. * assignedTo member 1 .. * * Student attends * 1 .. * teaches Course * * 1 .. * Instructor 0 .. 1 chairperson Relationship Modeling Technique UML에서 관계를 Modeling하려면 Modeling 대상 관계가 구조적이 아닌 경우에만 의존 사용 일반화는 “is-a-kind-of” 관계일 때만 사용하며 다중 상속은 집합 연관으로 표현 순환하는 일반화 관계는 표현하지 않도록 유의 일반화 관계를 전체적으로 균형 있게 유지(상속 계층이 너무 깊거 나, 넓지 않도록) 연관은 객체간에 구조적 관계가 있을 때 사용 Class Diagram Describes the types of objects in the system and various kinds of static relationships that exist among them. Shows attributes and operations of a class and constraints that apply to the way objects are connected Can be drawn from three different perspectives: conceptual, specification and implementation Class Diagramming Perspectives Conceptual Model represents the concepts in the domain under study describes business architecture rather than software architecture in a programming language-independent way Specification Model represents the interfaces of the software, not the implementation describes types rather than classes in OO language e.g., Java beans, CORBA, COM, Cool:Gen component interfaces Implementation Model defining classes in OO languages most often used perspective to date Example: Class Diagram Relationship between Class & Interaction Diagrams Services provided concurrently Security Officer A :Controller :SecurityEvent :Person :PermissionProfile reportSituation reportEvent alarmReport accessReport reportPerson personReport reportProfile * profileReport {B - A <= 5 sec} B * Patient Hospital admits situationReport 1 customer 1 * * Admission contract This association required to kill CAD associationCOD link error msg 1 is specified by 1 contract expert 1 * Physician is prescribed by 1 expert plan * * * * CarePlan 1.1: checkPrivileges 1: registerAdmission (physicianIdentification, patientName, patientDateOfBirth) 1 1.2: registerPatient (patientName, patientDateOfBirth) :Admission :Patient contract Admission Coordinator privilege expert is fulfilled by :Physician refers to plan TreatmentType 1 t_descriptor * tracks * customer contract 1.3: registerCarePlan TreatmentSpecification 1 plan requires :CarePlan * Date Time * is described by commitment This association required to kill CAD associationCOD link error msg ResourceSpecification * ResourceType Admission Coordinator :CarePlan :TreatmentSpecification specifyResources :TreatmentType specifyResources listResources resourceList resourceList resourceSummary resourceListOK resourceListOK registerResourceSpecification :ResourceSpecification resourceSpecificationRegistered resourcesSpecified :ACTOR_SchedulingSubsytem resourcesSpecified signal_resourcesSpecified Interaction diagrams coalesce into class diagram(s): objects into classes, links into associations Class with Stereotype / Property A persistent class is described by putting {persistent} property in the name compartment. Conceptual, spec. and implem. classes are described using «type» and «implementation class» stereotypes. Classes can be stereotyped to «entity», «boundary» and «controller» based on the model-view-controller concept (data-UI-logic layers). Conceptual or specification class Implementation class Stereotype icon Entity Boundary Interface and Abstract Class An interface is a class with no implementation (i.e., no objects) An interface is often declared through abstract class. has operation declaration but no method bodies and no fields. Subclassing provides the implementation, but clients never see the implementation, only the interface. Abstract class allows you to add implementation of some of the methods; an interface forces you to defer definition of all methods. Abstract classes are described by {abstract} property in the name compartment. Refinement is a relationship between two descriptions of the same thing, but at different levels of abstraction (levels of detail). A class that uses the interface implemented in another class is connected via a dependency relationship to the interface circle. Interface Refinement Dependency Parameterized Class A template is the descriptor for a class with one or more unbound formal parameters. Defines a family of classes, each class specified by binding the parameters to actual values. Attributes and operations within the template are defined in terms of the formal parameters. Association Conceptual level: semantics as in ERD Specification level: responsibilities (i.e., interface) e.g., an Order must come from a single Customer, and a Customer may make several Orders over time e.g., there are one or more methods assoc. w/ Customer that tell what orders a given Customer has made, and those assoc. w/ Order telling which Customer placed a given Order; further, Customer could be specified in the constructor for Order. Implementation level: physical implementation e.g., Customer has a field that is a collection of pointers to Orders. Customer 1 * Order Association Each association has two roles, one for each direction. Role name: verb phrase or noun (responsibility or operation). Multiplicity : 0..1; 1 (default); * (0..); 1..*; 2,4; 5. Navigability: An arrow at the end of the association line indicates that the assoc. can be used in only that direction. Meaningful only in spec. and implem. diagrams. Association Association name Multiplicity Role Reflexive association Or constraint Adornments on Assoc. Roles N-side -- {ordered}, {multiset}, {ordered multiset}, {tree}, {directed tree}, etc. Visibility -- public (+), private (), protected (#) Qualified Association Admission Hospital Name NumberOfBeds AHAClassification Hospital Name NumberOfBeds AHAClassification 1 authorizes AdmissionId * Date Type Partial key of the weak entity Admission Date 1 authorizes 1 Type AdmissionId Weak entity type “Given a Hospital and an AdmissionId, there can be only one Admission.” Association Class Allows to add attributes and operations to associations There can be only one instance of the assoc. class between any pair of participating objects (like the associative entity type in the data model). If a person can have more than one job in a company, you need to promote the assoc. class to a full class. Associative entity type Example: Association Class Admission AdmissionId Date Type ScheduleNew Reschedule Hospital Name NumberOfBeds AHAClassification * * serves Patient Name PatientId N-ary Association Each instance of the association is an n-tuple of values from the respective classes. The multiplicity on a role represents the potential number of instance tuples in the association when the other N-1 values are fixed. Association class Person * Assignment startDate endDate cancel 1 * Project Role Generalization Conceptual level: supertype/subtype relationship as in ERD Specification level: Interface of the subtype must include all elements from (or must conform to) the interface of the supertype. E.g. a Corporate Customer can substitute a Customer within any code requiring a Customer. The Corporate Customer may respond differently from Personal Customer when the same operation, creditRating, is called. -- Polymorphism Implementation level: subclassing, i.e., inheritance of all the methods and fields of the superclass in programming language Customer Corporate Customer Personal Customer Example: Generalization Admission AdmissionId Date Type ScheduleNew Reschedule InPatientAdmission RoomType PlannedLengthOfStay RecordNewAdmision ChangeRoomType UpdatePlannedStay OutPatientVisitAdmission Reason TypeOfVisit ReasonForVisit RecordVisit Classification Discriminator Multiple classification (Multiple inheritance) Aggregation Whole-part relationship Navy * Warship normal aggregation - 1:N * * Person Team shared aggregation - M:N composition aggregation - 1:N owner relationship Example: Aggregation TreatmentHistory Status NextTreatment 1 record of AddTreatment * CompletedTreatment Name Date Duration TreatmentNote RecordTreatment CarePlan LastUpdated CompletionDate UpdateCompDate 1 * PrescribedTreatment * NursingOrder Name Strength Duration TreatmentNote Name Instructions Note RecordTreatment RecordNote Derived Association / Attributes Derived assoc. and attributes can be calculated from other assoc. or attributes, resp. {Frozen} constraint can be used to indicate for an attribute or role, that its value may not change during the lifetime of the source object. {Read-only} indicates that a value cannot be changed directly, but may change due to a change in some other values. Object Diagram An object is an instance of a class. An object diagram shows specific instances of classes in a class diagram and links between the instances at some point in time. It can be thus viewed as an example of a class diagram. It uses the same notation as the class diagram. Object name format: object name: class name Node * * Connects Class Diagram Node 1 Node 2 Node 3 Node 4 Object Diagram Example : Customer order from a retail catalog Example : Rational Rose Class Diagram Example : Rational Rose Class Tool