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

169
www.profesorjava.com 1 PJ-010 Introducción al Análisis y Diseño Orientado a Objetos

Upload: profesorjavacom

Post on 18-Dec-2014

3.437 views

Category:

Education


7 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Introducción al Análisis y Diseño Orientado a Objetos

www.profesorjava.com 1

PJ-010

Introducción al Análisis y Diseño

Orientado a Objetos

Page 2: 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.

Page 3: Introducción al Análisis y Diseño Orientado a Objetos

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.

[email protected]

Page 4: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 5: Introducción al Análisis y Diseño Orientado a Objetos

5

Course Overview

• Object-oriented analysis and design

• Basic syntax for Java classes and structure of

Java program

• Unified Modeling Language (UML) notation

Page 6: Introducción al Análisis y Diseño Orientado a Objetos

6

Course Map

Page 7: Introducción al Análisis y Diseño Orientado a Objetos

7

Course Map

Page 8: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 9: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 10: Introducción al Análisis y Diseño Orientado a Objetos

10

Course Objectives

• Implement the understanding gained through OO and

Java technology syntax by developing UML diagrams to

analyze a problem domain

Page 11: Introducción al Análisis y Diseño Orientado a Objetos

11

1. Objects

Page 12: Introducción al Análisis y Diseño Orientado a Objetos

12

Module Goal

• This module defines objects and describes how to

identify objects within a problem domain.

Page 13: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 14: Introducción al Análisis y Diseño Orientado a Objetos

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)

Page 15: Introducción al Análisis y Diseño Orientado a Objetos

15

Overview of Object Orientation.

Page 16: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 17: Introducción al Análisis y Diseño Orientado a Objetos

17

Abstraction.

Page 18: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 19: Introducción al Análisis y Diseño Orientado a Objetos

19

Identifying Objects.

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

identity that encapsulates state and behavior.

Page 20: Introducción al Análisis y Diseño Orientado a Objetos

20

Identifying Objects.

Page 21: Introducción al Análisis y Diseño Orientado a Objetos

21

Identifying Objects.

Physical entity

Conceptual entity

(Chemical process)

Software entity

(Linked list)

Page 22: Introducción al Análisis y Diseño Orientado a Objetos

22

Identifying Objects.

• Objects have many forms:

– Tangible things (Airplane, Computer, Car)

– Roles (Doctor, Teacher)

– Incidents (Meeting)

– Interactions (Interview, Agreement)

Page 23: Introducción al Análisis y Diseño Orientado a Objetos

23

Object definition. Case Study

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

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

Page 24: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 25: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 26: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 27: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 28: Introducción al Análisis y Diseño Orientado a Objetos

28

Object definition. Case Study

inventory

back-ordered items

system

Internet

business

year

month

order form

check

Page 29: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 30: Introducción al Análisis y Diseño Orientado a Objetos

30

Identifying Object Attributes and Operations

Page 31: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 32: Introducción al Análisis y Diseño Orientado a Objetos

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?

Page 33: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 34: Introducción al Análisis y Diseño Orientado a Objetos

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?

Page 35: Introducción al Análisis y Diseño Orientado a Objetos

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?

Page 36: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 37: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 38: Introducción al Análisis y Diseño Orientado a Objetos

38

Independent Existence.

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

the object must need to exist independently

Page 39: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 40: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 41: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 42: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 43: Introducción al Análisis y Diseño Orientado a Objetos

43

Encapsulation.

Page 44: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 45: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 46: Introducción al Análisis y Diseño Orientado a Objetos

46

Encapsulation. Case Study

Page 47: Introducción al Análisis y Diseño Orientado a Objetos

47

Encapsulation. Case Study

Page 48: Introducción al Análisis y Diseño Orientado a Objetos

48

Encapsulation. Case Study

Page 49: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 50: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 51: Introducción al Análisis y Diseño Orientado a Objetos

51

2. Classes

Page 52: Introducción al Análisis y Diseño Orientado a Objetos

52

Module Goal

• This module describes how to group objects in classes,

and how characteristics of a class are inherited.

Page 53: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 54: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 55: Introducción al Análisis y Diseño Orientado a Objetos

55

Class Overview.

• An object is an instance of a class.

Page 56: Introducción al Análisis y Diseño Orientado a Objetos

56

Class Overview.

A class is represented using a rectangle with compartments.

Page 57: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 58: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 59: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 60: Introducción al Análisis y Diseño Orientado a Objetos

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).

Page 61: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 62: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 63: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 64: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 65: Introducción al Análisis y Diseño Orientado a Objetos

65

Case Study

• For each object identified in the DirectClothing order entry

system, define a corresponding class.

Page 66: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 67: Introducción al Análisis y Diseño Orientado a Objetos

67

Generalization

A relationship among classes where one class shares the

structure and/or behavior of one or more classes.

Page 68: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 69: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 70: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 71: Introducción al Análisis y Diseño Orientado a Objetos

71

Inheritance

Page 72: Introducción al Análisis y Diseño Orientado a Objetos

72

Inheritance

Page 73: Introducción al Análisis y Diseño Orientado a Objetos

73

Inheritance

Page 74: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 75: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 76: Introducción al Análisis y Diseño Orientado a Objetos

76

Specialization

Specialization is inheritance with the addition and modification

of methods to solve a specific problem.

Page 77: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 78: Introducción al Análisis y Diseño Orientado a Objetos

78

Polymorphism

Polymorphism is the ability to hide many different

implementations behind a single interface.

Page 79: Introducción al Análisis y Diseño Orientado a Objetos

79

Polymorphism

Interfaces formalize polymorphism.

Page 80: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 81: Introducción al Análisis y Diseño Orientado a Objetos

81

3. Object Interaction

Page 82: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 83: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 84: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 85: Introducción al Análisis y Diseño Orientado a Objetos

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)

Page 86: Introducción al Análisis y Diseño Orientado a Objetos

86

Association and Composition.

• a

Page 87: Introducción al Análisis y Diseño Orientado a Objetos

87

Association and Composition.

• a

Page 88: Introducción al Análisis y Diseño Orientado a Objetos

88

Association and Composition.

• a

Page 89: Introducción al Análisis y Diseño Orientado a Objetos

89

Association and Composition.

• a

Page 90: Introducción al Análisis y Diseño Orientado a Objetos

90

Association and Composition.

• a

Page 91: Introducción al Análisis y Diseño Orientado a Objetos

91

Association and Composition.

• a

Page 92: Introducción al Análisis y Diseño Orientado a Objetos

92

Association and Composition.

• a

Page 93: Introducción al Análisis y Diseño Orientado a Objetos

93

Association and Composition.

• a

Page 94: Introducción al Análisis y Diseño Orientado a Objetos

94

Association and Composition.

• a

Page 95: Introducción al Análisis y Diseño Orientado a Objetos

95

Association and Composition.

• a

Page 96: Introducción al Análisis y Diseño Orientado a Objetos

96

Association and Composition.

• a

Page 97: Introducción al Análisis y Diseño Orientado a Objetos

97

Association and Composition.

• a

Page 98: Introducción al Análisis y Diseño Orientado a Objetos

98

Association and Composition.

• a

Page 99: Introducción al Análisis y Diseño Orientado a Objetos

99

4. Object Oriented Analysis

and Design Using UML

Page 100: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 101: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 102: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 103: Introducción al Análisis y Diseño Orientado a Objetos

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.”

Page 104: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 105: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 106: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 107: Introducción al Análisis y Diseño Orientado a Objetos

107

Use Case Diagrams.

Page 108: Introducción al Análisis y Diseño Orientado a Objetos

108

Use Case Diagrams.

Page 109: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 110: Introducción al Análisis y Diseño Orientado a Objetos

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."

Page 111: Introducción al Análisis y Diseño Orientado a Objetos

111

Example: Use Case Diagrams.

Restocking a soda machine is an important use case.

Page 112: Introducción al Análisis y Diseño Orientado a Objetos

112

Example: Use Case Diagrams.

Collecting the money

from a soda machine

is another

important use case.

Page 113: Introducción al Análisis y Diseño Orientado a Objetos

113

Example: Use Case Diagrams.

Page 114: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 115: Introducción al Análisis y Diseño Orientado a Objetos

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. "

Page 116: Introducción al Análisis y Diseño Orientado a Objetos

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).

Page 117: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 118: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 119: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 120: Introducción al Análisis y Diseño Orientado a Objetos

120

Use Case Diagrams.

Page 121: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 122: Introducción al Análisis y Diseño Orientado a Objetos

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).

Page 123: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 124: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 125: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 126: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 127: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 128: Introducción al Análisis y Diseño Orientado a Objetos

128

Example: Use Case Diagrams.

Actores que interactuan con el sistema:

Page 129: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 130: Introducción al Análisis y Diseño Orientado a Objetos

130

Example: Use Case Diagrams.

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

Page 131: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 132: Introducción al Análisis y Diseño Orientado a Objetos

132

Example: Use Case Diagrams.

Page 133: Introducción al Análisis y Diseño Orientado a Objetos

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).

Page 134: Introducción al Análisis y Diseño Orientado a Objetos

134

Example: Use Case Diagrams.

Page 135: Introducción al Análisis y Diseño Orientado a Objetos

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).

Page 136: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 137: Introducción al Análisis y Diseño Orientado a Objetos

137

Exercises: Use Case Diagrams.

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

Page 138: Introducción al Análisis y Diseño Orientado a Objetos

Curso Java U de O 2006 138

Use Case Diagrams.

Page 139: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 140: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 141: Introducción al Análisis y Diseño Orientado a Objetos

141

Sequence Diagrams.

Page 142: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 143: Introducción al Análisis y Diseño Orientado a Objetos

143

Sequence Diagrams.

:JuegodeDados dado1:Dados dado2:Dados

jugar() lanzar()

val1:=getValorMostrado()

lanzar()

val2:=getValorMostrado()

Page 144: Introducción al Análisis y Diseño Orientado a Objetos

144

Sequence Diagrams.

:Computer :PrintServer :Printer

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

print(arch)

Page 145: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 146: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 147: Introducción al Análisis y Diseño Orientado a Objetos

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

Page 148: Introducción al Análisis y Diseño Orientado a Objetos

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()

Page 149: Introducción al Análisis y Diseño Orientado a Objetos

149

Sequence Diagrams.

a1:Order b1:OrderLine

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

*[for each] subtotal()

OrderTotal()

Page 150: Introducción al Análisis y Diseño Orientado a Objetos

150

Sequence Diagrams.

Page 151: Introducción al Análisis y Diseño Orientado a Objetos

151

Sequence Diagrams.

Activation boxes represent the

time an object needs to

complete a task

Page 152: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 153: Introducción al Análisis y Diseño Orientado a Objetos

153

Sequence Diagrams.

Lifelines are vertical dashed

lines that indicate the object's

presence over time.

Page 154: Introducción al Análisis y Diseño Orientado a Objetos

154

Sequence Diagrams.

Objects can be terminated

early using an arrow labeled

"< < destroy > >" that points to

an X.

Page 155: Introducción al Análisis y Diseño Orientado a Objetos

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 [ ].

Page 156: Introducción al Análisis y Diseño Orientado a Objetos

156

Example:

Page 157: Introducción al Análisis y Diseño Orientado a Objetos

157

Example:

Page 158: Introducción al Análisis y Diseño Orientado a Objetos

158

Example:

Page 159: Introducción al Análisis y Diseño Orientado a Objetos

159

Example:

Page 160: Introducción al Análisis y Diseño Orientado a Objetos

160

Example:

Page 161: Introducción al Análisis y Diseño Orientado a Objetos

161

Example:

Page 162: Introducción al Análisis y Diseño Orientado a Objetos

162

Example:

Page 163: Introducción al Análisis y Diseño Orientado a Objetos

163

Example:

Page 164: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 165: Introducción al Análisis y Diseño Orientado a Objetos

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.

Page 166: Introducción al Análisis y Diseño Orientado a Objetos

166

Sequence Diagrams.

GENERAR EL DIAGRAMA DE SECUENCIA PARA LA

MAQUINA RECICLADORA.

Page 167: Introducción al Análisis y Diseño Orientado a Objetos

167

Sequence Diagrams.

Page 168: Introducción al Análisis y Diseño Orientado a Objetos

168

Sequence Diagrams.

Page 169: Introducción al Análisis y Diseño Orientado a Objetos

169

Sequence Diagrams.