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


Published on

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

Published in: Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

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

  1. 1. PJ-010 Introducción al Análisis y Diseño Orientado a Objetos 1
  2. 2. Esta obra está bajo una licencia Reconocimiento 2.5 México de Creative Commons. Para ver una copia de esta licencia, visite o envíe una carta a Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
  3. 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.
  4. 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. 5. Course Overview • Object-oriented analysis and design • Basic syntax for Java classes and structure of Java program • Unified Modeling Language (UML) notation 5
  6. 6. Course Map 6
  7. 7. Course Map 7
  8. 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. 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. 10. Course Objectives • Implement the understanding gained through OO and Java technology syntax by developing UML diagrams to analyze a problem domain 10
  11. 11. 1. Objects 11
  12. 12. Module Goal • This module defines objects and describes how to identify objects within a problem domain. 12
  13. 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. 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. 15. Overview of Object Orientation. 15
  16. 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
  17. 17. Abstraction. 17
  18. 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. 19. Identifying Objects. An object is an entity with a well-defined boundary and identity that encapsulates state and behavior. 19
  20. 20. Identifying Objects. 20
  21. 21. Identifying Objects. Physical entity Conceptual entity (Chemical process) Software entity (Linked list) 21
  22. 22. Identifying Objects. • Objects have many forms: – Tangible things (Airplane, Computer, Car) – Roles (Doctor, Teacher) – Incidents (Meeting) – Interactions (Interview, Agreement) 22
  23. 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. 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. 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. 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. 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. 28. Object definition. Case Study  inventory  back-ordered items  system  Internet  business  year  month  order form  check 28
  29. 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. 30. Identifying Object Attributes and Operations 30
  31. 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. 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. 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. 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. 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. 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. 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. 38. Independent Existence. • To be an object and not a characteristic of another object, the object must need to exist independently 38
  39. 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. 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. 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. 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
  43. 43. Encapsulation. 43
  44. 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. 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
  46. 46. Encapsulation. Case Study 46
  47. 47. Encapsulation. Case Study 47
  48. 48. Encapsulation. Case Study 48
  49. 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. 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
  51. 51. 2. Classes 51
  52. 52. Module Goal • This module describes how to group objects in classes, and how characteristics of a class are inherited. 52
  53. 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. 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. 55. Class Overview. • An object is an instance of a class. 55
  56. 56. Class Overview. A class is represented using a rectangle with compartments. 56
  57. 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. 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. 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. 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. 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. 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. 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. 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. 65. Case Study • For each object identified in the DirectClothing order entry system, define a corresponding class. 65
  66. 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. 67. Generalization A relationship among classes where one class shares the structure and/or behavior of one or more classes. 67
  68. 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. 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. 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
  71. 71. Inheritance 71
  72. 72. Inheritance 72
  73. 73. Inheritance 73
  74. 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. 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. 76. Specialization Specialization is inheritance with the addition and modification of methods to solve a specific problem. 76
  77. 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. 78. Polymorphism Polymorphism is the ability to hide many different implementations behind a single interface. 78
  79. 79. Polymorphism Interfaces formalize polymorphism. 79
  80. 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
  81. 81. 3. Object Interaction 81
  82. 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. 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. 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. 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
  86. 86. Association and Composition. • a 86
  87. 87. Association and Composition. • a 87
  88. 88. Association and Composition. • a 88
  89. 89. Association and Composition. • a 89
  90. 90. Association and Composition. • a 90
  91. 91. Association and Composition. • a 91
  92. 92. Association and Composition. • a 92
  93. 93. Association and Composition. • a 93
  94. 94. Association and Composition. • a 94
  95. 95. Association and Composition. • a 95
  96. 96. Association and Composition. • a 96
  97. 97. Association and Composition. • a 97
  98. 98. Association and Composition. • a 98
  99. 99. 4. Object Oriented Analysis and Design Using UML 99
  100. 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. 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. 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. 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. 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. 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. 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
  107. 107. Use Case Diagrams. 107
  108. 108. Use Case Diagrams. 108
  109. 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. 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. 111. Example: Use Case Diagrams. Restocking a soda machine is an important use case. 111
  112. 112. Example: Use Case Diagrams. Collecting the money from a soda machine is another important use case. 112
  113. 113. Example: Use Case Diagrams. 113
  114. 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. 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. 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. 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. 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. 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
  120. 120. Use Case Diagrams. 120
  121. 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. 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. 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. 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. 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. 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. 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. 128. Example: Use Case Diagrams. Actores que interactuan con el sistema: 128
  129. 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. 130. Example: Use Case Diagrams. Un item puede ser una Botella, un Tarro o una Jaba. 130
  131. 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. 132. Example: Use Case Diagrams. 132
  133. 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. 134. Example: Use Case Diagrams. 134
  135. 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. 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. 137. Exercises: Use Case Diagrams. Encontrar los casos de uso para las tareas uno y dos. 137
  138. 138. Use Case Diagrams. Curso Java U de O 2006 138
  139. 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. 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
  141. 141. Sequence Diagrams. 141
  142. 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. 143. Sequence Diagrams. :JuegodeDados dado1:Dados dado2:Dados jugar() lanzar() val1:=getValorMostrado() lanzar() val2:=getValorMostrado() 143
  144. 144. Sequence Diagrams. :Computer :PrintServer :Printer print(arch) print(arch) [no queue] print(arch) 144
  145. 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. 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. 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. 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. 149. Sequence Diagrams. a1:Order b1:OrderLine OrderTotal() *[for each] subtotal() Sintaxis: * [expresión-iteación ] mensaje 149
  150. 150. Sequence Diagrams. 150
  151. 151. Sequence Diagrams. Activation boxes represent the time an object needs to complete a task 151
  152. 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. 153. Sequence Diagrams. Lifelines are vertical dashed lines that indicate the object's presence over time. 153
  154. 154. Sequence Diagrams. Objects can be terminated early using an arrow labeled "< < destroy > >" that points to an X. 154
  155. 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. 156. Example: 156
  157. 157. Example: 157
  158. 158. Example: 158
  159. 159. Example: 159
  160. 160. Example: 160
  161. 161. Example: 161
  162. 162. Example: 162
  163. 163. Example: 163
  164. 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. 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
  167. 167. Sequence Diagrams. 167
  168. 168. Sequence Diagrams. 168
  169. 169. Sequence Diagrams. 169