introducción al análisis y diseño orientado a objetos

Post on 18-Dec-2014

3.438 Views

Category:

Education

7 Downloads

Preview:

Click to see full reader

DESCRIPTION

Introducción al Análisis y Diseño Orientado a Objetos. Desarrollado por ISC Raúl Oramas Bustillos. www.profesorjava.com

TRANSCRIPT

www.profesorjava.com 1

PJ-010

Introducción al Análisis y Diseño

Orientado a Objetos

Esta obra está bajo una licencia Reconocimiento 2.5 México de Creative Commons. Para ver una copia de esta licencia, visite http://creativecommons.org/licenses/by/2.5/mx/ o envíe una carta a Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.

Acerca de:

En la compilación de esta obra se utilizaron libros conocidos en el ambiente Java, gráficas, esquemas, figuras de sitios de internet, conocimiento adquirido en los cursos oficiales de la tecnología Java. En ningún momento se intenta violar los derechos de autor tomando en cuenta que el conocimiento es universal y por lo tanto se puede desarrollar una idea a partir de otra. La intención de publicar este material en la red es compartir el esfuerzo realizado y que otras personas puedan usar y tomar como base el material aquí presentado para crear y desarrollar un material mucho más completo que pueda servir para divulgar el conocimiento.

Atte. ISC Raúl Oramas Bustillos.

rauloramas@profesorjava.com

4

Course Goal

This course teaches basic object-oriented (OO)

concepts and object-oriented analysis and design

as they relate to Java technology, as well as basic

Java technology programming concepts.

5

Course Overview

• Object-oriented analysis and design

• Basic syntax for Java classes and structure of

Java program

• Unified Modeling Language (UML) notation

6

Course Map

7

Course Map

8

Modules

Module 1: Objects.

Module 2: Classes.

Module 3: Using Java classes.

Module 4: Using Java methods.

Module 5: Object interaction.

Module 6: Object-Oriented Analysis and Design Using

UML

9

Course Objectives

• Identify objects in a problem domain

• Group objects in classes

• Identify objects’ relationships to one another

• Use inheritance to create a specialized Java class

• Describe polymorphism

• Use encapsulation when creating Java classes

• Define methods for a class

• Describe basic Java technology programming structure

guidelines

10

Course Objectives

• Implement the understanding gained through OO and

Java technology syntax by developing UML diagrams to

analyze a problem domain

11

1. Objects

12

Module Goal

• This module defines objects and describes how to

identify objects within a problem domain.

13

Objectives

You should be able to:

• Describe abstraction and how it is used in object

orientation Identify objects and non-objects from a

problem domain.

• Describe object encapsulation

14

Overview of Object Orientation.

• Technique for system modeling

• Models the system as a number of related objects that

interact

• Similar to the way people view their environment

Object technology is a set of principles guiding software

construction together with languages, databases, and

other tools that support those principles. (Object

Technology: A Manager’s Guide, Taylor, 1997)

15

Overview of Object Orientation.

16

Abstraction.

• Is the process of ignoring details to concentrate on essential

characteristics

• Is the primary means of coping with complexity

• Simplifies user’s interaction with abstracted objects

• Has two types: functional abstraction and data abstraction

-A student is a person enrolled in classes at the university

-A professor is a person teaching classes at the university

-A course is a class offered by the university

17

Abstraction.

18

Identifying Objects.

• Object can be a sentence, bank

account, number, or car

• Objects are:

– Things

– Real or imaginary

– Simple or complex

An object is an entity with a well-defined boundary and

identity that encapsulates state and behavior.

19

Identifying Objects.

An object is an entity with a well-defined boundary and

identity that encapsulates state and behavior.

20

Identifying Objects.

21

Identifying Objects.

Physical entity

Conceptual entity

(Chemical process)

Software entity

(Linked list)

22

Identifying Objects.

• Objects have many forms:

– Tangible things (Airplane, Computer, Car)

– Roles (Doctor, Teacher)

– Incidents (Meeting)

– Interactions (Interview, Agreement)

23

Object definition. Case Study

• Throughout this course, a case study of a clothing catalog,

DirectClothing, Inc., will be used to illustrate concepts.

24

Object definition. Case Study

• Most projects start by defining the problem domain by

gathering customer requirements and by writing a

statement of scope that briefly states what you, the

developer, want to achieve.

• For example, a scope statement for the DirectClothing

project might be: “Create a system allowing order entry

people to enter and accept payment for an order.”

• After you have determined the scope of the project, you can

begin to identify the objects that will interact to solve the

problem.

25

Object definition. Case Study

• Object names are often nouns, such as “account” or

“shirt.” Object attributes are often nouns too, such as

“color” or “size.” Object operations are usually verbs or

noun-verb combinations, such as“display” or “submit

order.”

• Your ability to recognize objects in the world around you will

help you to better define objects when approaching a

problem using object-oriented analysis.

Solution

26

Object definition. Case Study

• The problem domain of the DirectClothing, Inc. case study

has the following nouns. Each could be an object in the

catalog’s order entry system.

catalog

clothing

subscribers

closeout items

monthly items

normal items

order

27

Object definition. Case Study

customer

CSR ( customer service representative)

order entry clerk

Supplier

Payment

warehouse

credit car

order entry

mail order

fax order

online order

28

Object definition. Case Study

inventory

back-ordered items

system

Internet

business

year

month

order form

check

29

Identifying Object Attributes and Operations

• Example:

– Cloud attributes: size, water content, shape

– Cloud operations: rain, thunder, snow

Attributes: an object’s characteristics

Operations: what an object can do

30

Identifying Object Attributes and Operations

31

Identifying Object Attributes and Operations. Case Study

• When you are attempting to assign operations to an object,

operations performed on an object are assigned to the

object itself. For example, in a bank an account can be

opened and closed, balanced and updated, receive

additional signers, and generate a statement. All of these

would be the Account object’s operations.

32

Identifying Object Attributes and Operations. Case Study

• For the Order object, the following attributes and operations

could be defined:

– Attributes: orderNumber, customerNumber,

dateOrdered, amountOwed

– Operations: whatCustomer, calcAmountOwed,

printOrder, payOrder

• What would be the attributes and operations for the

Customer object?

33

Testing an Identified Object:

• Use the following criteria to test object validity:

– Relevance to the problem domain

– Need to exist independently

– Having attributes and operations

34

Relevance to the Problem Domain.

• Does it exist within the boundaries of the problem

statement?

• Is it required in order for the system to fulfill its

responsibility?

• Is it required as part of interaction between a user and the

system?

• Can objects sometimes be a characteristic of other objects?

35

Testing an Identified Object. Case Study

• The Order object exists within the boundaries of the

problem statement, it is required for the system to fulfill its

responsibilities, and as part of an interaction between a

user and the system. The Order object passes the test.

• Test the other candidate objects in the case study. What are

the results?

36

Testing an Identified Object. Case Study

The following objects can probably be removed from the list:

• Internet, system, business – Not necessary within the

boundaries of the problem statement

• month, year – May be attributes of the date of an order

being placed, but not necessary as an object itself

37

Testing an Identified Object. Case Study

The following objects can probably be removed from the list:

• online order, fax order, mail order – Can probably be

captured as special cases of the order object, or you could

have a type attribute on the order object to indicate how the

order was made. You may not want to eliminate here, but to

note these nouns are special cases.

• back-ordered items, closeout items, monthly sales item –

Can probably be captured as special cases of a normal item

object. You may not want to eliminate these nouns, but to

note these are special cases.

38

Independent Existence.

• To be an object and not a characteristic of another object,

the object must need to exist independently

39

Independent Existence. Case Study

• Can an Order object exist without any of the other objects?

It can, but in use, it must have an associated Customer

object.

• Address could be an attribute of Customer, but in this

case study it is advantageous for Address to be a separate

object.

40

Attributes and Operations.

• An object must have attributes and operations

• If it does not, it is probably and attribute or operation of

another object

41

Attributes and Operations. Case Study

• An object must have attributes and operations. If you

cannot define attributes and operations for an object, then it

probably is not an object but an attribute or operation of

another object.

• The Order object has many attributes and operations

defined, as do most of the candidate objects.

42

Encapsulation.

• Encapsulation separates the external aspects of an object

from the internal implementation details

• Internal changes need not affect external interface

Hide

implementation

from clients.

Clients depend

on interface

43

Encapsulation.

44

Implementing Encapsulation.

• An object’s attributes and operations are its members

• The members of an object can be public or private

• In pure OO systems, all attributes are private and can be

changed or accessed only through public operations

45

Encapsulation. Case Study

• Using the Order object from the case study, you would

make all attributes private and need to create public

operations to get and set values for each of the attributes.

All other operations, such as calcAmountOwed and

payOrder, would also be public. However, you could decide

that the calcAmountOwed should be private so other

objects cannot have access to calculate the amount owed.

46

Encapsulation. Case Study

47

Encapsulation. Case Study

48

Encapsulation. Case Study

49

Module summary

• Object. Representation of things; problem statement nouns

• Attributes. Characteristics or features of an object; data

• Operations. What an object does

• Abstraction. Process of Ignoring details

• Data hiding. Private member attributes

• Encapsulate. Separate internal details (hidden from other objects) from external aspects of an object (accessible by other objects); implement user’s needs

• Member. The makeup of an object; data and methods

50

Lab Time 01: Identifying Objects.

• Exercise objective – Identify the objects in a problem domain.

• Preparation – Review the case study

• Tasks – Complete the following steps:

1. Identify the candidate objects.

2. Identify attributes and operations for those objects.

3. Test for valid objects.

4. Encapsulate the valid objects.

51

2. Classes

52

Module Goal

• This module describes how to group objects in classes,

and how characteristics of a class are inherited.

53

Objectives

You should be able to:

• Group objects with similar attributes and common

operations in classes

• Explain how classes are used to define objects

• Define inheritance and explain how it relates to software

reuse

• Define generalization and specialization and how they

relate to inheritance

• Define polymorphism and explain how inheritance

promotes polymorphism

• Define abstract classes

54

Class Overview.

• A class is a description of a set of objects that share the

same attributes, operations, relationships, and

semantics.

– An object is an instance of a class.

• A class is an abstraction in that it Emphasizes relevant

characteristics. Suppresses other characteristics.

55

Class Overview.

• An object is an instance of a class.

56

Class Overview.

A class is represented using a rectangle with compartments.

57

Class Overview.

• A class is an abstract definition of an object. It defines the

structure and behavior of each object in the class. It serves

as a template for creating objects.

• Classes are not collections of objects.

58

Class Overview.

• An attribute is a named property of a class that describes a

range of values that instances of the property may hold.

• A class may have any number of attributes or no attributes

at all.

59

Class Overview.

• An operation is the implementation of a service that can be

requested from any object of the class to affect behavior.

• A class may have any number of operations or none at all.

60

Example.

Modelar una biblioteca sencilla que incluya las siguientes

características:

• De cada libro tengo uno o varios ejemplares.

• Cada usuario puede mantener un máximo de tres

ejemplares en préstamo de forma simultánea.

• Los usuarios pueden solicitar al bibliotecario un libro en

préstamo (dando el autor o el título, etc.) y el sistema debe

determinar si hay al menos un ejemplar en las estanterías.

Si es así, el bibliotecario entrega un ejemplar y registra el

préstamo (usuario, fecha y ejemplar concreto).

61

Example.

• El préstamo es semanal y si se produce un retraso en la

devolución, se impone una multa en forma de días sin

derecho a nuevos préstamos (3 días por cada día de

retraso). Antes de cualquier préstamo, el bibliotecario debe

comprobar esta situación.

62

Example.

cd Diagrama de Clases

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version

Libro

- autor: char

- isbn: char

- nombre: char

Ejemplar

- l ibro: Libro

- numeroEjemplar: int

Bibliotecario

- claveBibliotecario: char

- nombreBibliotecario: double

Prestamo

- bibliotecario: Bibliotecario

- ejemplar: Ejemplar

- fechaDevolucion: char

- fechaPrestamo: char

- numeroPrestamo: int

+ calcularMulta() : void

+ entregarEjemplar() : void

+ registrarDevolucion() : void

+ registrarPrestamo() : void

+ validarPrestamo() : void

+ verificarDisponibil idad() : void

Usuario

- claveUsuario: char

- nombreUsuario: char

- prestamo: Prestamo

63

Example.

Identificar los objetos (atributos y operaciones) para una

compañía de seguros de coches con un conjunto de clientes,

cada uno de los cuales es propietario de un número de

coches. Cada coche tiene asociado un número de accidentes

registrados.

64

Example.

Prepare una lista de objetos:

El Departamento de Control Escolar de la Universidad de

Occidente mantiene datos sobre cada asignatura, incluyendo

el profesor, lista de alumnos y la hora y lugar de clases. Para

cada par-estudiante se registra una calificación.

65

Case Study

• For each object identified in the DirectClothing order entry

system, define a corresponding class.

66

Generalization

Generalization identifies and defines the common attributes

and operations in a collection of objects.

Example: Transport is a generalization of several classes that

provide transportation.

67

Generalization

A relationship among classes where one class shares the

structure and/or behavior of one or more classes.

68

Case Study

When evaluating the objects for customer service

representative and order entry clerk, it was determined that

they are identical and that an employee class will be created.

You can instantiate an Employee class and create a

CustomerServiceRepresentative or an OrderEntryClerk object.

69

Case Study

When you evaluate the attributes and operations of the

Customer object and the Employee class, you will see some

similarities. Each has some unique number, firstName,

lastName, middleInitial, and address information. You could

create a Person class that would contain those similar

attributes; you could also create an Address class since the

Customer object has two addresses.

70

Inheritance

• Is a mechanism for defining a new class in terms of an

existing class.

• Allows you to group related classes so that they can be

managed collectively.

• Promotes reuse.

• Allows you to hide or override inherited members.

• Relevant terms: generalization, specialization, override.

71

Inheritance

72

Inheritance

73

Inheritance

74

Case Study

The DirectClothing

company uses a Person

object from which it

inherits general

information such as

name and ID. Both the

Customer and

Employee classes

extend Person.

75

Example

Una editorial de libros y discos desea crear fichas que

almacenen el título y precio (de tipo float) de cada

publicación. Crear la correspondiente clase (denominada

Publicación) que implemente los datos anteriores. A partir de

esta clase, diseñar dos clases derivadas: Libro, con el

número de páginas (tipo int), año de publicación (tipo int) y

precio (tipo float); y disco, con duración en minutos (tipo

float) y precio (int). Cada una de las clases tendrá una

función leer() y otra función mostrar(), para visualizar los

datos. Dibujar el diagrama de clases correspondiente.

76

Specialization

Specialization is inheritance with the addition and modification

of methods to solve a specific problem.

77

Polymorphism

• Allows you to implement an inherited operation in a

subclass

• Works only when the common operation gives the same

semantic result

• Implementation of a polymorphic function depends on the

object it is applied to

• Can be used only with inheritance

78

Polymorphism

Polymorphism is the ability to hide many different

implementations behind a single interface.

79

Polymorphism

Interfaces formalize polymorphism.

80

Case Study

In the order-entry system, you could use polymorphism with

The giveName operation for the Person object. The

specialized subclasses, Employee and Customer, would

inherit the giveName operation. The Employee object might

use the definition of the giveName operation as is (as inherited

and defined in the superclass Person). However, for the

Customer class, you might want a salutation to be used with

their name. So you would implement the giveName operation

to provide for this.

81

3. Object Interaction

82

Module Goal

• This module describes how objects interact, and how to

decide whether an object relationship should be one of

composition or association. The concepts of object

custody and lifetime are also discussed.

83

Objectives

You should be able to:

• Explain how objects interact with each other through

object messaging

• Define association

• Define composition

• Decide whether a relationship between two objects

should be association or composition

• Define the lifetime of an object with regard to association

and composition

• Define the custody of an object with regard to

association and composition

84

Object Messaging.

• One object sends a message to another (the receiving

object)

• The receiving object may send other messages, change its

attribute, or read in any other appropriate way.

• Messaging in handled by operations in the public interface

of the receiving object.

85

Association and Composition.

• Objects interact through one of two relationships:

association or composition.

• Association: Two independent objects collaborate to

achieve some goal, like a person using a computer (“uses a

” relationship)

• Composition: One object contains another, like a pencil that

has a lead (“has a” relationship)

86

Association and Composition.

• a

87

Association and Composition.

• a

88

Association and Composition.

• a

89

Association and Composition.

• a

90

Association and Composition.

• a

91

Association and Composition.

• a

92

Association and Composition.

• a

93

Association and Composition.

• a

94

Association and Composition.

• a

95

Association and Composition.

• a

96

Association and Composition.

• a

97

Association and Composition.

• a

98

Association and Composition.

• a

99

4. Object Oriented Analysis

and Design Using UML

100

Module Goal

• This module will give an overview of object-oriented

analysis and design (OOA/D) and show how to use

Unified Modeling Language (UML) to notate the design.

101

Objectives

You should be able to:

• Create a set of use cases to describe a problem domain

• Create a sequence diagram for a use case

• Create a class diagram for a problem domain

• Create an activity diagram for a use case

• Code class declarations for the class diagram

102

Object-Oriented Analysis and Design.

• Unified Modeling Language (UML) is used to notate the

design.

• UML diagrams:

– Use case diagram

– Sequence diagram

– Class diagrams

– Activity diagrams

103

Use Case Diagrams.

• A use case diagram contains use cases, actors, and

relationship links

• A use case is an interaction of a user with the application in

order to achieve a desired result

• An actor is a role that a user plays when interfacing with the

application

• Relationship links between use cases are “uses” and

“extends.”

104

Use Case Diagrams.

• There are two types of relationship links that can be made

in the diagram. These are the extends and uses

relationships between the use cases.

• The extends relationship links two use cases that are

similar but one does a little more than the other. It is implied

that the actor who performs the first use case will also

perform the extension use case. This relationship is

indicated by <<extends>> on the link’s line.

105

Use Case Diagrams.

• The second type of link is the uses relationship, which

occurs when there is a behavior that is used by many use

cases. To avoid repetition, make that behavior a use case

itself, and have other use cases “use” it. It is implied that an

actor does not perform the “used” use case, but that the

base use case does the performing.

• This relationship is indicated by <<uses>> on the link’s line.

106

Use Case Diagrams.

• An actor represents anything that interacts with the system.

• A use case is a sequence of actions a system performs that

yields an observable result of value to a particular actor.

107

Use Case Diagrams.

108

Use Case Diagrams.

109

Use Case Diagrams.

Follow these steps to create a use case diagram:

1. Identify each use case in your application. (It might help to

identify events you need to react to.)

2. Draw and label each of the actors of the application.

3. Draw and label the use cases of the application.

4. Draw the links from the actor to the use cases they

perform.

5. Write a short description of each use case. The diagram

and the description together will give a representation of

the functionality that must be implemented in the system.

110

Example: Use Case Diagrams.

A use case specifies a set of scenarios

for accomplishing something

useful for an actor. In this

example, one use case is

"Buy soda."

111

Example: Use Case Diagrams.

Restocking a soda machine is an important use case.

112

Example: Use Case Diagrams.

Collecting the money

from a soda machine

is another

important use case.

113

Example: Use Case Diagrams.

114

Use Case Diagrams.

Use case diagrams describe what a system does from the

standpoint of an external observer. The emphasis is on what

a system does rather than how.

Use case diagrams are closely connected to scenarios. A

scenario is an example of what happens when someone

interacts with the system.

115

Use Case Diagrams.

Here is a scenario for a medical clinic:

"A patient calls the clinic to make an appointment for a

yearly checkup. The receptionist finds the nearest empty time

slot in the appointment book and schedules the appointment

for that time slot. "

116

Use Case Diagrams.

A use case is a summary of scenarios for a single task or

goal. An actor is who or what initiates the events involved in

that task. Actors are simply roles that people or objects play.

The picture below is a Make Appointment use case for the

medical clinic. The actor is a Patient. The connection between

actor and use case is a communication association (or

communication for short).

Curso Java U de O 2006 117

Use Case Diagrams.

A use case diagram is a collection of actors, use cases, and

their communications. We've put Make Appointment as part of

a diagram with four actors and four use cases. Notice that a

single use case can have multiple actors.

118

Use Case Diagrams.

A use case describes a single task or goal and is indicated by

an oval. The task or goal is written inside the oval and usually

it contains a verb.

119

Use Case Diagrams.

TIP: Start by listing a sequence of steps a user might take in

order to complete an action. For example a user placing an

order with a sales company might follow these steps.

1. Browse catalog and select items.

2. Call sales representative.

3. Supply shipping information.

4. Supply payment information.

5. Receive conformation number from salesperson.

120

Use Case Diagrams.

121

Exercises: Use Case Diagrams.

Diseñar diagramas de casos de uso para las siguientes

situaciones:

• Comprar una paleta en la cafetería de la escuela.

• Cancelar una cita con el(la) novio(a) ó una salida con los

amigos.

• Enviar un mensaje de correo electrónico.

• Enviar un mensaje de texto de un teléfono celular a otro.

• Copiar un archivo a la memoria USB.

• Imprimir un documento de Word en el centro de cómputo.

122

Use Case Relations.

<<extend>> (extensión) : Los casos de uso pueden

extenderse a otros casos de uso. Se recomienda utilizar

cuando un caso de uso es similar a otro (características).

123

Use Case Relations.

<<include>> (inclusión) : Los casos de uso pueden incluir a

otros casos de uso. Se recomienda utilizar cuando se tiene

un conjunto de características que son similares en más de

un caso de uso y no se desea mantener copiada la

descripción de la característica.

124

Use Case Relations.

<<include>>

Cuando un número de casos de uso comparten un

comportamiento común puede ser descrito por un caso de

uso que es utilizado por otros casos de uso.

125

Use Case Relations.

<<extends>>

Es una relación de dependencia donde un caso de uso

extiende otro caso de uso añadiendo acciones a un caso de

uso extendido.

126

Example: Use Case Diagrams.

Máquina Recicladora: Sistema que controla una máquina

de reciclamiento de botellas, tarros y jabas. El sistema debe

controlar y/o aceptar:

• Registrar el número de ítems ingresados.

• Imprimir un recibo cuando el usuario lo solicita:

• Describe lo depositado

• El valor de cada item

• Total

127

Example: Use Case Diagrams.

• Existe un operador que desea saber lo siguiente:

– Cuantos ítems han sido retornados en el día.

– Al final de cada día el operador solicita un resumen de

todo lo depositado en el día.

• El operador debe además poder cambiar:

– Información asociada a ítems.

– Dar una alarma en el caso de que:

• Item se atora.

• No hay más papel.

128

Example: Use Case Diagrams.

Actores que interactuan con el sistema:

129

Example: Use Case Diagrams.

Un Cliente puede depositar Items y un Operador puede

cambiar la información de un Item o bien puede Imprimir un

Informe.

130

Example: Use Case Diagrams.

Un item puede ser una Botella, un Tarro o una Jaba.

131

Example: Use Case Diagrams.

la impresión de comprobantes, que puede ser realizada

después de depositar algún item por un cliente o bien puede

ser realizada a petición de un operador.

132

Example: Use Case Diagrams.

133

Example: Use Case Diagrams.

Sistema de ventas. Un sistema de ventas debe interactuar

con clientes, los cuales efectúan pedidos. Además los clientes

pueden hacer un seguimiento de sus propios pedidos. El

sistema envía los pedidos y las facturas a los clientes. En

algunos casos, según la urgencia de los clientes, se puede

adelantar parte del pedido (pedidos parciales).

134

Example: Use Case Diagrams.

135

Exercises: Use Case Diagrams.

Encontrar los casos de uso para la biblioteca sencilla:

• De cada libro tengo uno o varios ejemplares.

• Cada usuario puede mantener un máximo de tres

ejemplares en préstamo de forma simultánea.

• Los usuarios pueden solicitar al bibliotecario un libro en

préstamo (dando el autor o el título, etc.) y el sistema

debe determinar si hay al menos un ejemplar en las

estanterías. Si es así, el bibliotecario entrega un

ejemplar y registra el préstamo (usuario, fecha y ejemplar

concreto).

136

Exercises: Use Case Diagrams.

• El préstamo es semanal y si se produce un retraso en la

devolución, se impone una multa en forma de días sin

derecho a nuevos préstamos (3 días por cada día de

retraso).

• Antes de cualquier préstamo, el bibliotecario debe

comprobar esta situación.

137

Exercises: Use Case Diagrams.

Encontrar los casos de uso para las tareas uno y dos.

Curso Java U de O 2006 138

Use Case Diagrams.

139

Sequence Diagrams.

• Capture the operations of a single use case and show

how groups of objects collaborate on those operations.

• Exist for each use case.

• Contains objects, objects lifelines, messages between

objects, conditions, iteration markers, activations, and

object deletions.

140

Sequence Diagrams.

• A Sequence Diagram is an interaction diagram that

emphasizes the time ordering of messages.

• The diagram show:

– The objects participating in the interaction

– The sequence of messages exchanged

141

Sequence Diagrams.

142

Sequence Diagrams.

:Sistema

crearNuevaVenta()

*[más items]

descripción, total

:cajero

ingresarItem(codItem, cant)

finalizarVenta()

total con imptos.

realizarPago()

monto cambio, recibo

Bucle

Un diagrama de secuencia del sistema muestra, para un escenario particular de un caso de uso, los eventos externos que los actores generan, su orden y los eventos inter-sistemas.

143

Sequence Diagrams.

:JuegodeDados dado1:Dados dado2:Dados

jugar() lanzar()

val1:=getValorMostrado()

lanzar()

val2:=getValorMostrado()

144

Sequence Diagrams.

:Computer :PrintServer :Printer

print(arch) print(arch) [no queue]

print(arch)

145

Sequence Diagrams.

:Computer :PrintServer :Printer

print(arch) print(arch) [no queue]

print(arch)

Mensaje

Línea de vida

Activación

Mensaje Sincrónico

Retorno

Condición

Objetos participantes en la interacción

Puede omitirse

146

Sequence Diagrams.

:ItemWindow

:Item

NuevoItem(data)

crearItem(data)

Flecha hacia un objeto

índica creación del objeto.

:ItemWindow :Item EliminarItem()

BorrarItem() X

X indica destrucción del objeto

147

Sequence Diagrams.

Mensaje Simple / Sincrónico No se dan detalles de la comunicación cuando no

son conocidos o no son relevantes.

Mensaje Asincrónico

Sintaxis del mensaje: Número de secuencia [condición] * [expresión iteración]

valor de retorno := nombre del mensaje (parámetros)

Respuesta / Resultado

148

Sequence Diagrams.

a1:ClaseA b1:ClaseB

u Una ramificación es mostrada por múltiples mensaje que

abandonan un mismo punto, cada una etiquetada con una

condición

u Si las condiciones son mutuamente excluyentes representan

condiciones; de otra manera representan concurrencia.

:ClaseC [x>0] Op1()

X

[x<0] Op1()

149

Sequence Diagrams.

a1:Order b1:OrderLine

Sintaxis: * [expresión-iteación ] mensaje

*[for each] subtotal()

OrderTotal()

150

Sequence Diagrams.

151

Sequence Diagrams.

Activation boxes represent the

time an object needs to

complete a task

152

Sequence Diagrams.

Messages are arrows that represent

communication between objects.

Use half-arrowed lines to represent

asynchronous messages.

Asynchronous messages are sent

from an object that will not wait for a

response from the receiver before

continuing its tasks.

153

Sequence Diagrams.

Lifelines are vertical dashed

lines that indicate the object's

presence over time.

154

Sequence Diagrams.

Objects can be terminated

early using an arrow labeled

"< < destroy > >" that points to

an X.

155

Sequence Diagrams.

A repetition or loop within a

sequence diagram is depicted

as a rectangle. Place the

condition for exiting the loop at

the bottom left corner in

square brackets [ ].

156

Example:

157

Example:

158

Example:

159

Example:

160

Example:

161

Example:

162

Example:

163

Example:

164

Sequence Diagrams.

Follow these steps to create a sequence diagram. (These are

General guidelines; to write a sequence diagram you must

make sure you check for all interactions among all objects.)

1. Select a use case.

2. Add the first object in the use case to the diagram.

3. Add its method, the message it sends to the next object,

and the next object.

4. Check whether the second object replies to the first or

sends on another message and add the appropriate

elements.

165

Sequence Diagrams.

5. Repeat steps 3 and 4 as necessary.

6. Add any necessary elements mentioned in this section such

as conditions, iteration markers, or object deletions.

166

Sequence Diagrams.

GENERAR EL DIAGRAMA DE SECUENCIA PARA LA

MAQUINA RECICLADORA.

167

Sequence Diagrams.

168

Sequence Diagrams.

169

Sequence Diagrams.

top related