39
SYSC 3100 System Analysis and Design Classes Diagrams: Class features

SYSC 3100 System Analysis and Design Classes Diagrams: Class features

Embed Size (px)

Citation preview

SYSC 3100 System Analysis and Design

Classes Diagrams:

Class features

Objectives

• To understand a “Class” in the context of a UML class diagram.– Operations and attributes– Visibility– Scope– Properties of attributes and operations.

• To describe the difference between an interface and a class.

Textbook Reading

• Chapter 4 • Read through (some of the material is not covered in the

slides)• Write down questions related to material covered in the

book and ask them at the beginning of class or during office hours

• Look at solved problems and review questions

Introduction

• Class diagrams shows, in a graphical manner, the building blocks of any object-oriented system, its structure

• Classes, relationships between classes (potential for collaboration)

• Classes can be seen as user-defined types (in the programming language sense)

• Many of them tend to map concepts/entities of the application domain, but not all

• Many types of relationships, with specific semantics: associations, aggregation, composition, inheritance

Example

StaffMember

staffName

staffNo

staffStartDate

Client

companyAddress

companyEmail

companyFax

companyName

companyTelephone

liaises with

staffContact

Purpose

• Used throughout the development process• Describe, in a visual form, the static structure of

systems/subsystems at a certain level of abstraction• Features of classes: attributes, operations, relationships• Behavioral and data management responsibilities of

classes• Do not show the functional requirements of a system (use

case models)• Do not show how classes interact at run time (interaction

diagrams)

Class Diagram and Development Process

• Different stages: Analysis, high-level design (architecture), low-level design

• Class diagram will be described at different levels of detail depending on the stage of development (SYSC 4800)

• Analysis stage: classes reflecting entities from the application (problem) domain and their dependencies

• As we move into design, we add classes (among other things) to move towards an implemented solution

• Solution classes, e.g., interface, persistent data management

• A larger number of them will be included in the class diagram as we get closer to implementation

Class Diagram: Class Symbol

Client

companyAddresscompanyEmailcompanyFaxcompanyName

companyTelephone

Class name compartment

Attributes compartment

Operations compartment

Object/Instance Diagram: Instance/Object Symbol

FoodCo:Client

companyAddress=Evans Farm, Norfolk

[email protected]

companyFax=01589-008636

companyName=FoodCo

companyTelephone=01589-008638

Object name compartment

Attribute values

Instances do not have operations

Class Diagram: Stereotypes

• Analysis class stereotypes differentiate the roles objects can play:– Boundary objects model interaction between the system

and actors – Entity objects represent information and behaviour in

the application domain– Control objects co-ordinate and control other objects

(Control flow of Use Case scenario executions)• Q: Why would such a division of responsibilities be

useful?

Class Diagram: Stereotypes

User Interface::AddAdvertUI

User Interface::AddAdvertUI

startInterface( )assignStaff( )selectClient( )selectCampaign( )

<<boundary>>User Interface::AddAdvertUI

startInterface( )assignStaff( )selectClient( )selectCampaign( )

Alternative notations for boundary class:

We will stick with the left-most notation.

Class Diagram: Stereotypes

Alternative notations for entity class:

Campaign

Campaign

titlecampaignStartDatecampaignFinishDate

getCampaignAdverts( )addNewAdvert( )

<<entity>>Campaign

titlecampaignStartDatecampaignFinishDate

getCampaignAdverts( )addNewAdvert( )

We will stick with the left-most notation.

Class Diagram: Stereotypes

Alternative notations for control class:

AddAvert

Control::AddAdvert

showClientCampaigns( )showCampaignAdverts( )createNewAdvert( )

<<control>>Control::AddAdvert

showClientCampaigns( )

showCampaignAdverts( )

createNewAdvert( )

Entity Classes: University Enrolment System

Degree

degree_name : Stringtotal_credit_points : Integer

Course

course_code : Stringcourse_name : Stringcredit_points : Integer

Student

student_id : Stringstudent_name : String

CourseOffering

year : Datesemester : Integerenrolment_quota : Integer

StudyProgram

year : Datesemester : Integer

Attributes

• Attribute: a named property of a class that describes a range of values that instances of the property may hold

• Attribute type: Either UML predefined types, model types, or programming language types

• Each attribute has one value for each object– At a given moment, an object of a class will have specific values for

every one of it’s class attributes

• Normally there is no need for an explicit “ID” attribute: The object identity is characterized by one or more attributes

• Attribute name:– Capitalize the first letter of every word in an attribute name except the

first letter, e.g., studentNumber

Attributes

• Listed in the list compartment underneath the name box

Shuttle

weight : Integerage : Integer

Mission

start : Dateend : Datecost : Dollars

Customer

nameaddressphone

birthDate

Type

Attributes

• Syntax of an attribute in the UML:[visibility] name [multiplicity] [:type] [= initial-value] [{property-string}]

• Examples

origin // name only

+ origin // visibility and name

origin : Point // name and type

name [0..1] : String // name, multiplicity, and type

origin : Point = (0,0) // name, type, and initial value

id : Integer {readOnly} // name, type, and property

Derived attribute

-lastname : String-dateofBirth : Date-dateRegistered : Date-/age : Integer

CarSharer

{age = today - dateOfBirth}

• Derived attributes are used to specify attributes whose value is the result of a computation, based on other attribute values: attribute name is preceded by a “/”.

• Usage: show relationships between attributes explicitly, Save computation time (at the expense of memory) for commonly used attributes that can be derived

Visibility• The visibility of an attribute specifies whether it can be used by other classes.

(information hiding) • Four levels of visibility:

– any outside class with visibility to the given class can use the feature

– specified by prepending the symbol +public

protected– any descendant of the classifier can use the feature– specified by prepending the symbol #

private– only the class itself can use the feature– specified by prepending the symbol -

- only classifiers declared in the same package can

use the feature

- specified by prepending the symbol ~

package

Visibility

Window

+ size : Area = (100, 100)# visibility : Boolean = invisible+ default-size: Rectangle# maximum-size: Rectangle- xptr: Xwindow*

• In a pure object-oriented system, most attributes are private.

• Attribute values are hidden from other classes.

• Objects of one class can only request the services (by executing operations) published in the public interface of another class.

• They are not allowed to directly manipulate other objects’ attributes.

• Encapsulation, information hiding

Multiplicity of an attribute

• Multiplicity: specifies the range of allowable cardinalities an attribute may assume

• The range of values is written between brackets• The default value is 1• Examples:

– [0..1]– [2..*]

• General Definition of Multiplicity: A specification of a range of allowable cardinalities an entity may assume. This will also be used for classes, associations, etc.

Properties of an attribute

• Property: a named value denoting a characteristic of an attribute. Each attribute can be suffixed with a property enclosed in curly braces ({…})

• Properties for an attribute:– Unless otherwise specified, attributes are always

changeable– Readonly property is used to indicate that the

attribute’s value may not be changed after the object is initialized.

– The readonly property maps to const in C++

Operations

• Operation: the implementation of a service that you can request on any object of the class– An abstraction of something you can do to an object and that is

shared by all objects of that class

• A class may have any number of operations or no operation at all

• Often (but not always), invoking an operation on an object changes the object’s data or state

• Are listed in an additional box underneath the attribute box using a specific syntaxname (arg1 : type, arg2 : type ...) : return type

Operations

Shuttle

start_engines (throttle : Integer)stop_engines ()fuel_level (): integer

weight age : Integer

Rectangle

add()grow()move()

isEmpty()

Operations

• Syntax of an operation in the UML:[visibility] name [(parameter-list)] [: return-type] [{property-string}]

• Syntax of a parameter list in the UML:[direction] name : type [= default-value]

• Examples

display // name only

+ display // visibility and name

set(n: Name, s: String) // name and parameters

getId(): Integer // name and return type

restart() {guarded} // name and property

bind(in i:item, in v:value) // name and parameter with directions (kind)

Operation Visibility

• The visibility of an operation specifies whether it can be used by other classes.

• Three levels of visibility (no default value):public (+)protected (#)private (-)Package (~)

+display+hide+create-attachXWindow(xwin:Xwindow*)

+size : Area = (100, 100)#visibility : Boolean+default-size: Rectangle#maximum-size: Rectangle-xptr: Xwindow*

Window

Visibility should be decided carefully based on needs of client classes and subclasses

Operation Parameters

• Each parameter in the list: <parameterName>:<type>– approveApplication(dateApproved:Date)

• Can omit the parameter name– approveApplication(Date)

• Default value for parameter: suffix a parameter with =<defaultValue>– approveApplication(dateApproved:Date = today)

• Parameter kind: in (default), out, inout• Operations can be grouped by stereotypes: <<constructor>>,

<<query>>, <<update>>

Properties of an operation

leaf // The operation is not polymorphic and may not be overridden

isQuery // Execution of the method leaves the state of the system unchanged. No side effect

sequential // callers must ensure that only one flow of control is in the object at a time. Otherwise, the semantics and integrity of the object cannot be guaranteed. The operation is intended only for use in a single thread of control.

Five possible properties for an operation. Each operation can be suffixed with a property list in the form of a list of “tagged values” enclosed in curly braces ({…})

Properties of an operationguarded // Semantics and integrity of the object is guaranteed in the presence of multiple flows of control

Calls are sequentialized to all of the object’s guarded operations. Exactly one operation at a time can be invoked on the object. The operation will work in the presence of multiple threads of control, but it needs an active collaboration of the threads to achieve mutual exclusion, e.g., use of semaphores.concurrent // Multiple calls from concurrent flows of control may occur simultaneously to one object on any concurrent operation, and all may proceed concurrently with correct semantics. The operation will work in the presence of multiple threads of control; the class itself handles this. This feature is being built in some modern programming languages, e.g., Java synchronized

Static The operation does not have an implicit parameter for the target object; it behaves like a traditional global procedure.

Java reminder: Usage of Synchronized

class MyClass {synchronized void aMethod() {

(do something)}

}

class MyClass {void aMethod() {

Synchronized(this) {(do something)}

}}

Scope

• The owner scope of an attribute (respectively an operation) specifies whether the attribute (the operation) appears in each instance of the class or whether there is just a single instance of the feature for all instances of the class.

• In the UML, there are two kinds of owner scope:– instance each instance of the class holds its

ownvalue (definition) for the attribute(operation)

– class there is just one value (definition) of the

attribute (operation) for all instances of

the class

Scope

• The class scope is rendered by underlining the attribute (operation)

• Attribute (operation) at the class scopeClass (operation) attribute• Do not apply to an instance, but to the class (e.g.,

constructors)

Frame

header: FrameHeaderuniqueId: Long

Car

– numCars: Int…

– increaseNumCars()…

Class Multiplicity

• How many instances of a specific class will be created at runtime?– Zero: for an abstract class, or if you want the class to

expose only class scope attributes and operations– One: this is a singleton– X (a specific number)– Many (default)

Class Multiplicity

• The multiplicity of a class is written in the upper-right corner of the class icon

NetworkController

consolePort [2..*]: Port

1 ControlRod 3

Singleton design pattern Implementation(C++)

class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance;};

Singleton* Singleton::Instance () { if (_instance == 0) { _instance = new Singleton(); } return _instance;}

Interfaces• An interface is a collection of public attributes and

operations that must be implemented by the classes that implement the interface or that are required by the classes that depend upon the interface.

• An interface specifies a contract for a class or a component without dictating its implementation.

• Graphically, an interface may be rendered as a stereotyped class in order to expose its operations and other properties (cf. figure below)

«interface»URLStreamHandler

openConnection()parseURL()setURL()toExternalForm()

Interfaces cont.

• Interfaces cannot be instantiated• Many programming languages support the concept of

interfaces, including Java, Objective C and Ada. (C++ too)• In Java, interfaces cannot specify attributes• Interfaces are used to decouple client classes from server

classes whose implementation may change: clients depends only on an interface that may eventually be implemented in a different way.

• Like a class, an interface may participate in generalization, association, and dependency relationships (part II).

• In addition, an interface may participate in realization relationships (part II).

Sales System Example

Summary

• Class diagrams describe the “types” and “interfaces” of software. Their relationships to each other will be covered later.

• Visibility defines the ability of other classes to access the attributes and operations of a given class.

• Scope defines per-instance or global access for an operation or attribute. Public and private are the important ones. Attributes should always be private.

• Properties define some special characteristic (such as being read-only) of operations and attributes.