SlideShare a Scribd company logo
1 of 169
Download to read offline
PJ-010
Introducción al Análisis y Diseño
      Orientado a Objetos




            www.profesorjava.com    1
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
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.




                                                      4
Course Overview
• Object-oriented analysis and design
• Basic syntax for Java classes and structure of
  Java program
• Unified Modeling Language (UML) notation




                                                   5
Course Map




             6
Course Map




             7
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




                                                          8
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


                                                           9
Course Objectives
• Implement the understanding gained through OO and
  Java technology syntax by developing UML diagrams to
  analyze a problem domain




                                                     10
1. Objects




             11
Module Goal
• This module defines objects and describes how to
  identify objects within a problem domain.




                                                     12
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




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

                                                              14
Overview of Object Orientation.




                                  15
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


                                                             16
Abstraction.




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

                                                           18
Identifying Objects.




 An object is an entity with a well-defined boundary and
 identity that encapsulates state and behavior.

                                                           19
Identifying Objects.




                       20
Identifying Objects.

Physical entity



Conceptual entity
(Chemical process)



Software entity
(Linked list)

                       21
Identifying Objects.

• Objects have many forms:
  –   Tangible things (Airplane, Computer, Car)
  –   Roles (Doctor, Teacher)
  –   Incidents (Meeting)
  –   Interactions (Interview, Agreement)




                                                  22
Object definition. Case Study

• Throughout this course, a case study of a clothing catalog,
  DirectClothing, Inc., will be used to illustrate concepts.




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

                                                            24
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


                                                              25
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

                                                          26
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
                                             27
Object definition. Case Study

   inventory
   back-ordered items
   system
   Internet
   business
   year
   month
   order form
   check



                                28
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

                                                       29
Identifying Object Attributes and Operations




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




                                                          31
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?

                                                            32
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




                                                        33
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?




                                                           34
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?




                                                                35
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




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

                                                            37
Independent Existence.

• To be an object and not a characteristic of another object,
  the object must need to exist independently




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




                                                          39
Attributes and Operations.

• An object must have attributes and operations
• If it does not, it is probably and attribute or operation of
  another object




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




                                                             41
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



                                                          42
Encapsulation.




                 43
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




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




                                                           45
Encapsulation. Case Study




                            46
Encapsulation. Case Study




                            47
Encapsulation. Case Study




                            48
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




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


                                                              50
2. Classes




             51
Module Goal
• This module describes how to group objects in classes,
  and how characteristics of a class are inherited.




                                                           52
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
                                                          53
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.




                                                                54
Class Overview.

• An object is an instance of a class.




                                         55
Class Overview.

A class is represented using a rectangle with compartments.




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




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




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




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


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




                                                           61
A 5.1 Unregistered Trial Version                          EA 5.1 Unregistered Trial Version                      E
   Example.
A 5.1 Diagrama de Clases Trial Version
   cd
      Unregistered                                        EA 5.1 Unregistered Trial Version                      E

A 5.1 Unregistered Trial Version emplar 5.1 Unregistered Trial Version
          Libro                Ej  EA                 Bibliotecario                                              E
      -       autor: char                     -   libro: Libro                -   claveBibliotecario: char
      -       isbn: char                      -   numeroEjemplar: int         -   nombreBibliotecario: double
A 5.1 Unregistered Trial Version
      -       nombre: char                                EA 5.1 Unregistered Trial Version                      E

A 5.1 Unregistered Trial Version                          EA 5.1 Unregistered Trial Version                      E

A 5.1 Unregistered Trial Version                          EA 5.1 Unregistered Trial Version                      E
                       Prestamo                                         Usuario

       - bibliotecario: Bibliotecario
A 5.1 Unregistered Trial Version
       - ejemplar: Ejemplar
                                                          EA 5.1 Unregistered Trial Version
                                                            -
                                                            -
                                                              claveUsuario: char
                                                              nombreUsuario: char
                                                                                                                 E
          -    fechaDevolucion: char                          -   prestamo: Prestamo
          -    fechaPrestamo: char
A 5.1 Unregistered Trial Version
          -    numeroPrestamo: int                        EA 5.1 Unregistered Trial Version                      E
          +    calcularMulta() : void
A 5.1 Unregistered Trial Version
       + entregarEjemplar() : void                        EA 5.1 Unregistered Trial Version                      E
          +    registrarDevolucion() : void
          +    registrarPrestamo() : void
A 5.1 Unregistered Trial Version
          +    validarPrestamo() : void                   EA 5.1 Unregistered Trial Version                      E
          +    verificarDisponibilidad() : void


A 5.1 Unregistered Trial Version                          EA 5.1 Unregistered Trial Version                      E
                                                                                                            62
A 5.1 Unregistered Trial Version                          EA 5.1 Unregistered Trial Version                      E
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.




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




                                                            64
Case Study

• For each object identified in the DirectClothing order entry
  system, define a corresponding class.




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




                                                              66
Generalization

A relationship among classes where one class shares the
structure and/or behavior of one or more classes.




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




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




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




                                                              70
Inheritance




              71
Inheritance




              72
Inheritance




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



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


                                                           75
Specialization

Specialization is inheritance with the addition and modification
of methods to solve a specific problem.




                                                             76
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




                                                        77
Polymorphism

Polymorphism is the ability to hide many different
implementations behind a single interface.




                                                     78
Polymorphism

Interfaces formalize polymorphism.




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




                                                             80
3. Object Interaction




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




                                                           82
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
                                                           83
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.




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




                                                           85
Association and Composition.

• a




                               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
4. Object Oriented Analysis
  and Design Using UML




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




                                                      100
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




                                                        101
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




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




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




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




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




                                                           106
Use Case Diagrams.




                     107
Use Case Diagrams.




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

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




                                          110
Example: Use Case Diagrams.

Restocking a soda machine is an important use case.




                                                      111
Example: Use Case Diagrams.

Collecting the money
from a soda machine
is another
important use case.




                              112
Example: Use Case Diagrams.




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




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




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




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




                       Curso Java U de O 2006            117
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.




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



                                                            119
Use Case Diagrams.




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


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




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




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




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




                                                       125
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



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


                                                         127
Example: Use Case Diagrams.

Actores que interactuan con el sistema:




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




                                                         129
Example: Use Case Diagrams.

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




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




                                                         131
Example: Use Case Diagrams.




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




                                                          133
Example: Use Case Diagrams.




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


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




                                                        136
Exercises: Use Case Diagrams.

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




                                                        137
Use Case Diagrams.




                 Curso Java U de O 2006   138
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.




                                                           139
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




                                                         140
Sequence Diagrams.




                     141
Sequence Diagrams.

                                                         :Sistema
                 :cajero
                               crearNuevaVenta()

                           ingresarItem(codItem, cant)


                                  descripción, total
    Bucle
                                   *[más items]

                                 finalizarVenta()

                                  total con imptos.

                                 realizarPago()

                                monto cambio, recibo




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.
                                                                    142
Sequence Diagrams.




          :JuegodeDados                    dado1:Dados   dado2:Dados


        jugar()
                           lanzar()


                   val1:=getValorMostrado()


                                      lanzar()


                           val2:=getValorMostrado()




                                                                       143
Sequence Diagrams.


            :Computer                 :PrintServer            :Printer

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




                                                                         144
Sequence Diagrams.
                       Objetos participantes en la interacción


                :Computer                 :PrintServer            :Printer

      print(arch)           print(arch)             [no queue]           Condición
                                                    print(arch)
   Mensaje
                         Mensaje
                        Sincrónico
  Activación




     Línea de
       vida                 Retorno
                     Puede omitirse
                                                                               145
Sequence Diagrams.
                                      Flecha hacia un objeto
                     :ItemWindow    índica creación del objeto.
 NuevoItem(data)
                             crearItem(data)
                                                     :Item




                     :ItemWindow                     :Item
    EliminarItem()


                              BorrarItem()
                                                       X

                                         X indica destrucción del objeto

                                                                       146
Sequence Diagrams.
                    Mensaje Simple / Sincrónico
                    No se dan detalles de la comunicación cuando no
                    son conocidos o no son relevantes.

                    Respuesta / Resultado

                        Mensaje Asincrónico


Sintaxis del mensaje:
Número de secuencia [condición] * [expresión iteración]
     valor de retorno := nombre del mensaje (parámetros)

                                                                      147
Sequence Diagrams.

             a1:ClaseA       b1:ClaseB


                     [x<0] Op1()
                                         :ClaseC
                     [x>0] Op1()



                                           X

  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.

                                                                  148
Sequence Diagrams.


                a1:Order                       b1:OrderLine
 OrderTotal()
                           *[for each] subtotal()




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


                                                              149
Sequence Diagrams.




                     150
Sequence Diagrams.




                     Activation boxes represent the
                     time an object needs to
                     complete a task



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




                                                         152
Sequence Diagrams.

                     Lifelines are vertical dashed
                     lines that indicate the object's
                     presence over time.




                                                  153
Sequence Diagrams.

                     Objects can be terminated
                     early using an arrow labeled
                     "< < destroy > >" that points to
                     an X.




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




                                                  155
Example:




           156
Example:




           157
Example:




           158
Example:




           159
Example:




           160
Example:




           161
Example:




           162
Example:




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

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




                                                        165
Sequence Diagrams.

GENERAR EL DIAGRAMA DE SECUENCIA PARA LA
MAQUINA RECICLADORA.




                                           166
Sequence Diagrams.




                     167
Sequence Diagrams.




                     168
Sequence Diagrams.




                     169

More Related Content

Viewers also liked

Ejercicio de programación en java Club futbool
Ejercicio de programación en java Club futboolEjercicio de programación en java Club futbool
Ejercicio de programación en java Club futboolManuel Fco
 
Java Persistence Api (Jpa)
Java Persistence Api (Jpa)Java Persistence Api (Jpa)
Java Persistence Api (Jpa)Ronald Cuello
 
Introducción a la Programación con Java
Introducción a la Programación con JavaIntroducción a la Programación con Java
Introducción a la Programación con Javaflekoso
 
Calculo de Media, Mediana y MODA(una moda), Programación en JAVA
Calculo de Media, Mediana y MODA(una moda), Programación en JAVACalculo de Media, Mediana y MODA(una moda), Programación en JAVA
Calculo de Media, Mediana y MODA(una moda), Programación en JAVAkevin stanley pineda ramirez
 
Lenguaje de Programación Java
Lenguaje de Programación JavaLenguaje de Programación Java
Lenguaje de Programación JavaAlfredo Aguayo
 
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...Tino Fernández
 
Plan curso de programación java SE
Plan curso de programación java SEPlan curso de programación java SE
Plan curso de programación java SEDiego Rovalino
 

Viewers also liked (12)

Ejercicio de programación en java Club futbool
Ejercicio de programación en java Club futboolEjercicio de programación en java Club futbool
Ejercicio de programación en java Club futbool
 
Java Persistence Api (Jpa)
Java Persistence Api (Jpa)Java Persistence Api (Jpa)
Java Persistence Api (Jpa)
 
Java
JavaJava
Java
 
Introducción a la Programación con Java
Introducción a la Programación con JavaIntroducción a la Programación con Java
Introducción a la Programación con Java
 
Interfaz java y arduino
Interfaz java y arduinoInterfaz java y arduino
Interfaz java y arduino
 
Calculo de Media, Mediana y MODA(una moda), Programación en JAVA
Calculo de Media, Mediana y MODA(una moda), Programación en JAVACalculo de Media, Mediana y MODA(una moda), Programación en JAVA
Calculo de Media, Mediana y MODA(una moda), Programación en JAVA
 
Java orientado a objetos
Java orientado a objetosJava orientado a objetos
Java orientado a objetos
 
Lenguaje de Programación Java
Lenguaje de Programación JavaLenguaje de Programación Java
Lenguaje de Programación Java
 
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...
Libro de proyectos del kit oficial de Arduino en castellano completo - Arduin...
 
Curso Arduino práctico 2014
Curso Arduino práctico  2014Curso Arduino práctico  2014
Curso Arduino práctico 2014
 
Plan curso de programación java SE
Plan curso de programación java SEPlan curso de programación java SE
Plan curso de programación java SE
 
Core java slides
Core java slidesCore java slides
Core java slides
 

Similar to Introducción al Análisis y Diseño Orientado a Objetos

Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iTaymoor Nazmy
 
Handout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignHandout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignSAFAD ISMAIL
 
Object Modelling Technique " ooad "
Object Modelling Technique  " ooad "Object Modelling Technique  " ooad "
Object Modelling Technique " ooad "AchrafJbr
 
Object analysis and design
Object analysis and designObject analysis and design
Object analysis and designAnand Grewal
 
Object oriented analysis_and_design_v2.0
Object oriented analysis_and_design_v2.0Object oriented analysis_and_design_v2.0
Object oriented analysis_and_design_v2.0Ganapathi M
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and DesignRiazAhmad786
 
CEN6016-Chapter1.ppt
CEN6016-Chapter1.pptCEN6016-Chapter1.ppt
CEN6016-Chapter1.pptNelsonYanes6
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)MD Sulaiman
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Oo concepts and class modeling
Oo concepts and class modelingOo concepts and class modeling
Oo concepts and class modelingPreeti Mishra
 
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdf
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdfunit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdf
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdfRojaPogul1
 
Introduction to SAD.pptx
Introduction to SAD.pptxIntroduction to SAD.pptx
Introduction to SAD.pptxazida3
 
OOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptOOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptitadmin33
 

Similar to Introducción al Análisis y Diseño Orientado a Objetos (20)

Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
Handout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and DesignHandout on Object orienetd Analysis and Design
Handout on Object orienetd Analysis and Design
 
Object Modelling Technique " ooad "
Object Modelling Technique  " ooad "Object Modelling Technique  " ooad "
Object Modelling Technique " ooad "
 
Ooad unit – 1 introduction
Ooad unit – 1 introductionOoad unit – 1 introduction
Ooad unit – 1 introduction
 
ppt_ooad.pdf
ppt_ooad.pdfppt_ooad.pdf
ppt_ooad.pdf
 
Object analysis and design
Object analysis and designObject analysis and design
Object analysis and design
 
Object oriented analysis_and_design_v2.0
Object oriented analysis_and_design_v2.0Object oriented analysis_and_design_v2.0
Object oriented analysis_and_design_v2.0
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and Design
 
CEN6016-Chapter1.ppt
CEN6016-Chapter1.pptCEN6016-Chapter1.ppt
CEN6016-Chapter1.ppt
 
CEN6016-Chapter1.ppt
CEN6016-Chapter1.pptCEN6016-Chapter1.ppt
CEN6016-Chapter1.ppt
 
5-CEN6016-Chapter1.ppt
5-CEN6016-Chapter1.ppt5-CEN6016-Chapter1.ppt
5-CEN6016-Chapter1.ppt
 
80410172053.pdf
80410172053.pdf80410172053.pdf
80410172053.pdf
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Oo concepts and class modeling
Oo concepts and class modelingOo concepts and class modeling
Oo concepts and class modeling
 
01 chapter
01 chapter01 chapter
01 chapter
 
Chapter 06
Chapter 06Chapter 06
Chapter 06
 
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdf
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdfunit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdf
unit-1modellingconceptsclassmodeling-140929182538-phpapp01.pdf
 
Introduction to SAD.pptx
Introduction to SAD.pptxIntroduction to SAD.pptx
Introduction to SAD.pptx
 
OOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptOOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.ppt
 

Recently uploaded

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 

Recently uploaded (20)

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 

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

  • 1. PJ-010 Introducción al Análisis y Diseño Orientado a Objetos www.profesorjava.com 1
  • 2. 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.
  • 3. 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. 4
  • 5. Course Overview • Object-oriented analysis and design • Basic syntax for Java classes and structure of Java program • Unified Modeling Language (UML) notation 5
  • 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 8
  • 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 9
  • 10. Course Objectives • Implement the understanding gained through OO and Java technology syntax by developing UML diagrams to analyze a problem domain 10
  • 12. Module Goal • This module defines objects and describes how to identify objects within a problem domain. 12
  • 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 13
  • 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) 14
  • 15. Overview of Object Orientation. 15
  • 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 16
  • 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. 18
  • 19. Identifying Objects. An object is an entity with a well-defined boundary and identity that encapsulates state and behavior. 19
  • 21. Identifying Objects. Physical entity Conceptual entity (Chemical process) Software entity (Linked list) 21
  • 22. Identifying Objects. • Objects have many forms: – Tangible things (Airplane, Computer, Car) – Roles (Doctor, Teacher) – Incidents (Meeting) – Interactions (Interview, Agreement) 22
  • 23. Object definition. Case Study • Throughout this course, a case study of a clothing catalog, DirectClothing, Inc., will be used to illustrate concepts. 23
  • 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. 24
  • 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 25
  • 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 26
  • 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 27
  • 28. Object definition. Case Study  inventory  back-ordered items  system  Internet  business  year  month  order form  check 28
  • 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 29
  • 30. Identifying Object Attributes and Operations 30
  • 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. 31
  • 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? 32
  • 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 33
  • 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? 34
  • 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? 35
  • 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 36
  • 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. 37
  • 38. Independent Existence. • To be an object and not a characteristic of another object, the object must need to exist independently 38
  • 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. 39
  • 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 40
  • 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. 41
  • 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 42
  • 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 44
  • 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. 45
  • 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 49
  • 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. 50
  • 52. Module Goal • This module describes how to group objects in classes, and how characteristics of a class are inherited. 52
  • 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 53
  • 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. 54
  • 55. Class Overview. • An object is an instance of a class. 55
  • 56. Class Overview. A class is represented using a rectangle with compartments. 56
  • 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. 57
  • 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. 58
  • 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. 59
  • 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). 60
  • 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. 61
  • 62. A 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version E Example. A 5.1 Diagrama de Clases Trial Version cd Unregistered EA 5.1 Unregistered Trial Version E A 5.1 Unregistered Trial Version emplar 5.1 Unregistered Trial Version Libro Ej EA Bibliotecario E - autor: char - libro: Libro - claveBibliotecario: char - isbn: char - numeroEjemplar: int - nombreBibliotecario: double A 5.1 Unregistered Trial Version - nombre: char EA 5.1 Unregistered Trial Version E A 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version E A 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version E Prestamo Usuario - bibliotecario: Bibliotecario A 5.1 Unregistered Trial Version - ejemplar: Ejemplar EA 5.1 Unregistered Trial Version - - claveUsuario: char nombreUsuario: char E - fechaDevolucion: char - prestamo: Prestamo - fechaPrestamo: char A 5.1 Unregistered Trial Version - numeroPrestamo: int EA 5.1 Unregistered Trial Version E + calcularMulta() : void A 5.1 Unregistered Trial Version + entregarEjemplar() : void EA 5.1 Unregistered Trial Version E + registrarDevolucion() : void + registrarPrestamo() : void A 5.1 Unregistered Trial Version + validarPrestamo() : void EA 5.1 Unregistered Trial Version E + verificarDisponibilidad() : void A 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version E 62 A 5.1 Unregistered Trial Version EA 5.1 Unregistered Trial Version E
  • 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. 63
  • 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. 64
  • 65. Case Study • For each object identified in the DirectClothing order entry system, define a corresponding class. 65
  • 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. 66
  • 67. Generalization A relationship among classes where one class shares the structure and/or behavior of one or more classes. 67
  • 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. 68
  • 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. 69
  • 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. 70
  • 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. 74
  • 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. 75
  • 76. Specialization Specialization is inheritance with the addition and modification of methods to solve a specific problem. 76
  • 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 77
  • 78. Polymorphism Polymorphism is the ability to hide many different implementations behind a single interface. 78
  • 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. 80
  • 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. 82
  • 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 83
  • 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. 84
  • 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) 85
  • 99. 4. Object Oriented Analysis and Design Using UML 99
  • 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. 100
  • 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 101
  • 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 102
  • 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.” 103
  • 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. 104
  • 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. 105
  • 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. 106
  • 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. 109
  • 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." 110
  • 111. Example: Use Case Diagrams. Restocking a soda machine is an important use case. 111
  • 112. Example: Use Case Diagrams. Collecting the money from a soda machine is another important use case. 112
  • 113. Example: Use Case Diagrams. 113
  • 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. 114
  • 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. " 115
  • 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). 116
  • 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. Curso Java U de O 2006 117
  • 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. 118
  • 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. 119
  • 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. 121
  • 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). 122
  • 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. 123
  • 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. 124
  • 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. 125
  • 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 126
  • 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. 127
  • 128. Example: Use Case Diagrams. Actores que interactuan con el sistema: 128
  • 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. 129
  • 130. Example: Use Case Diagrams. Un item puede ser una Botella, un Tarro o una Jaba. 130
  • 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. 131
  • 132. Example: Use Case Diagrams. 132
  • 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). 133
  • 134. Example: Use Case Diagrams. 134
  • 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). 135
  • 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. 136
  • 137. Exercises: Use Case Diagrams. Encontrar los casos de uso para las tareas uno y dos. 137
  • 138. Use Case Diagrams. Curso Java U de O 2006 138
  • 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. 139
  • 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 140
  • 142. Sequence Diagrams. :Sistema :cajero crearNuevaVenta() ingresarItem(codItem, cant) descripción, total Bucle *[más items] finalizarVenta() total con imptos. realizarPago() monto cambio, recibo 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. 142
  • 143. Sequence Diagrams. :JuegodeDados dado1:Dados dado2:Dados jugar() lanzar() val1:=getValorMostrado() lanzar() val2:=getValorMostrado() 143
  • 144. Sequence Diagrams. :Computer :PrintServer :Printer print(arch) print(arch) [no queue] print(arch) 144
  • 145. Sequence Diagrams. Objetos participantes en la interacción :Computer :PrintServer :Printer print(arch) print(arch) [no queue] Condición print(arch) Mensaje Mensaje Sincrónico Activación Línea de vida Retorno Puede omitirse 145
  • 146. Sequence Diagrams. Flecha hacia un objeto :ItemWindow índica creación del objeto. NuevoItem(data) crearItem(data) :Item :ItemWindow :Item EliminarItem() BorrarItem() X X indica destrucción del objeto 146
  • 147. Sequence Diagrams. Mensaje Simple / Sincrónico No se dan detalles de la comunicación cuando no son conocidos o no son relevantes. Respuesta / Resultado Mensaje Asincrónico Sintaxis del mensaje: Número de secuencia [condición] * [expresión iteración] valor de retorno := nombre del mensaje (parámetros) 147
  • 148. Sequence Diagrams. a1:ClaseA b1:ClaseB [x<0] Op1() :ClaseC [x>0] Op1() X 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. 148
  • 149. Sequence Diagrams. a1:Order b1:OrderLine OrderTotal() *[for each] subtotal() Sintaxis: * [expresión-iteación ] mensaje 149
  • 151. Sequence Diagrams. Activation boxes represent the time an object needs to complete a task 151
  • 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. 152
  • 153. Sequence Diagrams. Lifelines are vertical dashed lines that indicate the object's presence over time. 153
  • 154. Sequence Diagrams. Objects can be terminated early using an arrow labeled "< < destroy > >" that points to an X. 154
  • 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 [ ]. 155
  • 156. Example: 156
  • 157. Example: 157
  • 158. Example: 158
  • 159. Example: 159
  • 160. Example: 160
  • 161. Example: 161
  • 162. Example: 162
  • 163. Example: 163
  • 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. 164
  • 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. 165
  • 166. Sequence Diagrams. GENERAR EL DIAGRAMA DE SECUENCIA PARA LA MAQUINA RECICLADORA. 166