A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Modelagem de Software Orientado a Objetos

Apresentações semelhantes


Apresentação em tema: "Modelagem de Software Orientado a Objetos"— Transcrição da apresentação:

1 Modelagem de Software Orientado a Objetos
PONTIFÍCIA UNIVERSIDADE CATÓLICA DE SÃO PAULO CURSO DE ESPECIALIZAÇÃO EM ENGENHARIA DE SOFTWARE Modelagem de Software Orientado a Objetos Modelagem de Software Orientado a Objetos Parte 2- Princípios de Modelagem UML Diagramas de Interação Prof. Maurício Nacib Pontuschka

2 Demonstrar como ler e interpretar:
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Introduce the objectives for this module. Objetivos Descrever a dinâmica comportamental e mostar como capturá-la em um modelo. Demonstrar como ler e interpretar: Um diagrama de seqüência Um diagrama de comunicação Explicar as similaridades e diferenças entre os diagramas de comunicação e de seqüência.

3 Objetos precisam colaborar
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Set the context of the module so that the students understand why interaction diagrams are needed. Objetos precisam colaborar Objetos são inúteis a não ser que possam colaborar na solução de problemas. Cada objeto é responsável por seu comportamentoe estado. Nenhum objeto pode assumir toda a responsabilidade sozinho. Como os objetos interagem entre si? Eles interagem por meio de mensagens. Objects need to realize the behavior specified in each use-case scenario. How is this done? The objects must collaborate together to bring about the desired behavior in the system. Is there a mechanism that allows these objects to work together? There is, and that mechanism is called a message.

4 Objetos interagem por meio de mensagens
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Explain how objects “talk” to each other when they collaborate. Messages are used by objects in the same way that messages are used by people. For example, an air traffic controller can send a message to an airplane pilot that it is ok to land. The pilot then lands the airplane (responsibility). After the plane is on the ground, the pilot sends a signal back to the air traffic controller (return value) that they have finished landing. Objetos interagem por meio de mensagens Uma mensagem mostra como um objeto pede a outro para que alguma atividade seja executada. : Car buyer :ControladorMatrícula :SistemaCatalogoCurso getOfertaCursos(semestre) Mensagem A message can be defined as: The specification of a communication among objects that conveys information with the expectation that activity will ensue. (The Unified Modeling Language User Guide, Booch, 1999.) When you pass a message, the action that results is an executable statement that forms an abstraction of a computational procedure. An action may result in a change of state. Messages are the mechanism that permits objects to interact with each other. A message is often implemented by a simple activity. For example, one object calls an operation in another. When the activity has been executed, the control is returned to the caller along with a return value.

5 O que é um diagrama de interações?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Introduce the concept of an interaction diagram for modeling object collaborations. Emphasize that interaction diagrams are used to model the dynamic aspects of a system. Static modeling is discussed in the class diagrams module. There is a tabular alternative to Interaction Diagrams in the UML 2 specification. It’s anticipated that there will be limited tool support for the tabular format so we don’t cover it. O que é um diagrama de interações? É um termo genárico que se aplica a vários diagramas que enfatizam as interações entre objetos Diagrama de Seqüência Diagrama de Comunicação Variantes Especializadas Diagrama de Tempo Diagrama Geral de Interação

6 Diagramas de Interação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Diagramas de Interação Diagrama de Seqüência Visão cronológica das interações dos objetos. Diagrama de Comunicação Visão estrutural das mensagens dos objetos. Diagramas de Seqüência The sequence diagram is a time-oriented view of the interaction between objects to accomplish a behavioral goal of the system. An interaction may be modeled at any level of abstraction within the system design, from subsystem interactions to instance-level interaction for a single operation or activity. The communication diagram is a structural view of the messaging between objects, taken from the Collaboration diagram concept of UML1. Diagramas de Comunicação

7 Diagramas de Interação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The interaction overview diagram is a variety of an activity diagram incorporating sequence diagram fragments in place of actions and activities. Diagramas de Interação Diagramas de Tempo Diagrama de Tempo Visão de restrições de tempo das mensagens envolvidas em uma interação. Diagrama Geral de Interação Visão de alto nível dos conjuntos de interação combinados em seqüências lógicas. Diagramas Gerais de Interações The timing diagram is an optional diagram designed to specify the time constraints on messages sent and received in the course of an interaction. This diagram probably has more usefulness in real-time applications where timing is critical. The interaction overview diagram is a high-level view of the sets of interactions combined into logic sequence, including flow-control logic to navigate between the interactions. Think of this as a cross between a Sequence Diagram, for the interactions sets, and an Activity Diagram, for the logic sequence.

8 Diagramas de Seqüência Diagramas de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The goal of this section is to introduce, not teach introductory topics about sequence diagrams. Onde estamos? Diagramas de Seqüência Diagramas de Comunicação Comparação dos diagramas de interação

9 O que é um diagrama de seqüência?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Messages are executed in sequence and take place over a certain period of time. O que é um diagrama de seqüência? Um diagrama de seqüência é um diagrama de interação que enfatiza a ordem cronológica de mensagens. O diagrama exibe: Os objetos que participam da interação. A seqüência de mensagens trocadas. A sequence diagram describes a pattern of interaction among objects, arranged in a chronological order. It shows the objects participating in the interaction by their "lifelines" and the messages that they send to each other. In most cases, we use a sequence diagram to illustrate use-case realizations. That is, realizations show how objects interact to perform the behavior of all or part of a use case. One or more sequence diagrams may illustrate the object interactions that enact a use case. A typical organization is to have one sequence diagram for the main flow of events and one sequence diagram for each independent sub-flow of the use case. Sequence diagrams are particularly important to designers because they clarify the roles of objects in a flow and provide basic information for determining class responsibilities and interfaces. Diagrama de seqüência

10 Exemplo: Diagrama de seqüência
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Exemplo: Diagrama de seqüência Have the students read through this diagram. Help them if they get stuck. The next few slides discuss the details of the items found on this diagram. Note: the purpose of this slide is to show how a sequence diagram fits together. There are no //’s because the // is a way to represent responsibilities. Responsibilities are discussed in the OOAD course but are outside the scope of this course. : Student :RegisterForCoursesForm :RegistrationController : Course Catalog :CourseCatalogSystem 1: create schedule( ) 5: display course offerings( ) 2: get course offerings( ) 3: get course offerings(forSemester) 6: display blank schedule( ) 4: get course offerings( ) Select Offerings ref You can have objects and actor instances in sequence diagrams, together with messages describing how they interact. The diagram describes what takes place in the participating objects, in terms of activations, and how the objects communicate by sending messages to one another. You can make a sequence diagram for each variant of a use case's flow of events. The above example shows the object interactions to support the Register for Courses’ use case, Create a Schedule sub-flow. Note the following responsibility allocation rationale. The RegisterForCoursesForm knows what data it needs to display and how to display it. It does not know where to go to get it. That is one of the RegistrationController’s responsibilities. Only the RegisterForCoursesForm interacts with the Student actor. The RegistrationController understands how Students and Schedules are related. Only the CourseCatalogSystem class interacts with the external legacy Course Catalog System. Note the inclusion of the actors. This is important as it explicitly models what elements communicate with the “outside world.”

11 Elementos do Diagrama de Seqüência: Objetos
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Explain objects on a sequence diagram. Make sure the students understand that this is an object diagram and not a class diagram. How do you know that these are objects and not classes? (The names are underlined.) Elementos do Diagrama de Seqüência: Objetos :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem Objetos anônimos Linhas de vida Objetos nomeados An object is shown as a vertical dashed line called the "lifeline." The lifeline represents the existence of the object at a particular time. An object symbol is drawn at the head of the lifeline, and shows the name of the object and its class underlined and separated by a colon: objectname : classname You can use objects in sequence diagrams in the following ways: A lifeline can represent an object. Thus, you can use a lifeline to model both class and object behavior. Usually, a lifeline represents all objects of a certain class. An object's class can be unspecified. Normally you create a sequence diagram with objects first and specify their classes later. The objects can be unnamed. However, name them if you want to discriminate different objects of the same class. Several lifelines in the same diagram can represent different objects of the same class. As stated previously, the objects should be named so that you can discriminate between the two objects. A lifeline that represents a class can exist in parallel with lifelines that represent objects of that class. The object name of the lifeline that represents the class can be set to the name of the class.

12 Elementos do Diagrama de Seqüência: Atores
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Elementos do Diagrama de Seqüência: Atores Explain actors on a sequence diagram. Human actors usually initiate action and are on the left side of the sequence diagram. If an actor is a passive recipient of information, they are on the right side. Avoid placing an actor in the middle of a set of objects. :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem : Student : Course Catalog Normally an actor instance is represented by the first (leftmost) lifeline in the sequence diagram, as the invoker of the interaction. If you have several actor instances in the same diagram, try keeping them either to the leftmost or to the rightmost lifelines. Don’t show the interaction between actors in a sequence diagram because actors are, by definition, external to the system. Instâncias de atores

13 Elementos do Diagrama de Seqüência: Mensagens
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Elementos do Diagrama de Seqüência: Mensagens Explain messages on a sequence diagram. Reflexive messages are usually not public messages. Normally, these messages are private. Conversely, messages that are invoked from another object must be public. :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem : Student : Course Catalog 1: create schedule( ) 2: get course offerings( ) 3: get course offerings(for Semester) A message is a communication between objects that conveys information with the expectation that activity will ensue. In sequence diagrams, a message is shown as a horizontal solid arrow from the lifeline of one object to the lifeline of another object. For a message from an object to itself, the arrow may start and finish on the same lifeline. The arrow is labeled with the name of the message and its parameters. The arrow may also be labeled with a sequence number to show the sequence of the message in the overall interaction. Sequence numbers are often omitted in sequence diagrams, where the physical location of the arrow shows the relative sequence. A message can be unassigned, meaning that its name is a temporary string that describes the overall meaning of the message. (// is a way to represent responsibilities and is discussed further in the OOAD course.) It is not the name of an operation of the receiving object. You can later assign the message by specifying the operation of the message's destination object. The specified operation then replaces the name of the message. 4: get course offerings( ) 5: display course offerings( ) 6: display blank schedule( ) Mensagem Mensagens Reflexivas

14 Elementos do Diagrama de Seqüência: Processo
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Elementos do Diagrama de Seqüência: Processo Explain execution occurrence on a sequence diagram. :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem : Student : Course Catalog 1: create schedule( ) 2: get course offerings( ) The execution occurrence is a tall, thin rectangle that shows the period of time during which an object is performing an action, either directly or through a subordinate procedure. The top of the rectangle is aligned with the start of the action. The bottom is aligned with its completion. In earlier UML releases, the execution occurrence was called the focus of control. This changed with UML 2. 3: get course offerings(for Semester) 4: get course offerings( ) 5: display course offerings( ) 6: display blank schedule( ) Processo em execução

15 Elementos do Diagrama de Seqüência: Ocorrência de evento
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Elementos do Diagrama de Seqüência: Ocorrência de evento Explain event occurrence on a sequence diagram. :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem : Student : Course Catalog 1: create schedule( ) 2: get course offerings( ) The event occurrence is the sending or receipt of a message by an object. An event occurrence is not explicitly shown as a separate modeling concept. It is normally shown by the intersection of the message with the lifeline. A message connects two event occurrences on two lifelines. 3: get course offerings(for Semester) 4: get course offerings( ) 5: display course offerings( ) 6: display blank schedule( ) Ocorrência de evento

16 Elementos do Diagrama de Seqüência: Ocorrência de Interação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Elementos do Diagrama de Seqüência: Ocorrência de Interação Explain interaction occurrence on a sequence diagram. 1: create schedule( ) 2: get course offerings( ) 3: get course offerings(for Semester) 4: get course offerings( ) 6: display blank schedule( ) :RegisterForCoursesForm :RegistrationController SWTSU Catalog : CourseCatalogSystem : Student : Course Catalog 5: display course offerings( ) Select Offerings ref Ocorrência de interação The interaction occurrence is a reference to an interaction within the definition of another interaction. An interaction occurrence is shown in a sequence diagram as a rectangle with the tag ref (for reference). The rectangle covers the lifelines that are included in the referenced interaction. The name of the referenced interaction is placed in the rectangle

17 Diagramas de Seqüência Diagramas de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The goal of this section is to introduce communication diagrams. Onde estamos? Diagramas de Seqüência Diagramas de Comunicação Comparação dos diagramas de interação

18 O que é um diagrama de comunicação?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Unlike sequence diagrams, communication diagrams emphasize the organization of the objects. Sequence diagrams, on the other hand, emphasize the time ordering of the messages. O que é um diagrama de comunicação? Um diagrama de comunicação enfatiza a organização de objetos em uma interação. Um diagrama de comunicação mostra: Os objetos que participam da interação. Ligações entre os objetos. Mensagens passadas entre os objetos. A communication diagram shows how objects interact to perform the behavior of a particular use case or a part of a use case. Like sequence diagrams, communication diagrams are used by designers to define and clarify the roles of the objects that perform a particular flow of events of a use case. They are the primary source of information used to determine class responsibilities and interfaces. Because of the communication diagram’s format, they tend to be better suited for analysis activities. Specifically, they tend to be better suited to depict simpler interactions of a smaller number of objects. As the number of objects and messages grows, the diagram becomes increasingly hard to read. It is also difficult to show additional descriptive information like timing, decision points, or other unstructured information that can be easily added to the notes in a sequence diagram. Diagramas de Interação

19 Exemplo: Diagrama de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Provide a preview of a communication diagram for the students. Explain how communication diagrams allow you to see the communication patterns among the objects. Normally, boundary classes are on the “edge,” interfacing with actors. Control classes are toward the middle, managing communication. Entity classes are on the “bottom” where all of the persistent data lives. Exemplo: Diagrama de Comunicação 5: display course offerings( ) 6: display blank schedule( ) 1: create schedule( ) : Course Catalog : RegisterForCoursesForm You can have objects and actor instances in communication diagrams, together with links and messages describing how they are related and how they interact. The diagram describes what takes place in the participating objects, in terms of how the objects communicate by sending messages to one another. You can make a communication diagram for each variant of a use case's flow of events. The above example shows the communication of objects to support the Register for Courses use case, Create a Schedule sub-flow. It is the “communication diagram equivalent” of the sequence diagram shown earlier. : Student 2: get course offerings( ) 4: get course offerings( ) 3: get course offerings(forSemester) : RegistrationController : CourseCatalogSystem

20 Elementos do Diagrama de Comunicação: Objetos
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Explain objects on a communication diagram. Make sure the students understand that this is an object diagram and not a class diagram. How do you know that these are objects and not classes? (The names are underlined.) Note: You don’t have to show the boundary, control, and entity stereotypes on a communication diagram, but they can help you see communication patterns quicker. Elementos do Diagrama de Comunicação: Objetos : RegisterForCoursesForm Objetos An object is represented by an object symbol, showing the name of the object and its class underlined, separated by a colon. objectname : classname You can use objects in communication diagrams in the following ways: An object's class can be unspecified. Normally, you create a communication diagram with objects first and specify their classes later. The objects can be anonymous. However, you should name them if you want to discriminate different objects of the same class. : RegistrationController SWTSU Catalog : CourseCatalogSystem

21 Elementos do Diagrama de Comunicação: Atores
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Explain actors on a communication diagram. Elementos do Diagrama de Comunicação: Atores : RegisterForCoursesForm : Student : Course Catalog Atores Normally an actor instance occurs in the communication diagram as the invoker of the interaction. If you have several actor instances in the same diagram, try to keep them in the periphery of the diagram. Don’t show the interaction between actors in a communication diagram because actors are, by definition, external to the system. : RegistrationController SWTSU Catalog : CourseCatalogSystem

22 Elementos do Diagrama de Comunicação: Ligações e mensagens
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Explain links and messages on a communication diagram. Point out that these are the same messages that were seen on the sequence diagram. Notice, however, that you have to follow the numbers to figure out the sequence. This diagram is more effective at pointing out the relationships between the objects. Elementos do Diagrama de Comunicação: Ligações e mensagens Mensagens 5: display course offerings( ) 6: display blank schedule( ) Ligações 1: create schedule( ) : Course Catalog A link is a relationship between objects across which messages can be sent. In communication diagrams, a link is shown as a solid line between two objects. An object interacts with or navigates to other objects through its links to these objects. A link can be an instance of an association. Or, it can be anonymous, meaning that its association is unspecified. Message flows are attached to links. A message is a communication between objects that conveys information with the expectation that activity will ensue. In communication diagrams, a message is shown as a labeled arrow placed near a link. That is, the link is used to transport or otherwise implement the delivery of the message to the target object. The arrow points along the link in the direction of the target object (the one that receives the message). The arrow is labeled with the name of the message and its parameters. The arrow may also be labeled with a sequence number to show the sequence of the message in the overall interaction. Sequence numbers are often used in communication diagrams because they are the only way to describe the relative sequencing of messages. : RegisterForCoursesForm : Student 2: get course offerings( ) 4: get course offerings( ) 3: get course offerings(forSemester) : RegistrationController : CourseCatalogSystem

23 Diagramas de Seqüência Diagramas de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The goal of this section is to introduce communication diagrams. Onde estamos? Diagramas de Seqüência Diagramas de Comunicação Comparação dos diagramas de interação

24 Similaridades entre os diagramas de Seqüência e de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Show the students the similarities between sequence and communication diagrams. Go back and point to the semantic similarities between the two diagrams. Similaridades entre os diagramas de Seqüência e de Comunicação São semanticamente equivalentes Podem ser convertidos de um para o outro sem perda de informação Modelam aspectos dinâmicos de um sistema Modelam o cenário de um caso de uso Because they both derive the same information from the UML’s metamodel; sequence diagrams and communication diagrams are semantically equivalent. As a result, you can take a diagram in one form and convert it to the other without any loss of information.

25 Diferenças entre diagramas de Seqüência e de Comunicação
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Show the students the differences between the two diagrams. The use of sequence versus communication diagrams is a personal choice. This course does not recommend one over the other, but describes the advantages of each. For brainstorming, some find the communication diagram easier, a closer visual representation of CRC cards. The students should use the diagram they like best. However, you may want to recommend that they ultimately create the communication diagram to find relationships between the associated classes. Note: RUP recommends that communication diagrams be used in analysis and that sequence diagrams be used in design. Diferenças entre diagramas de Seqüência e de Comunicação Diagramas de Seqüência Diagramas de Comunicação Exibem explicitamente a seqüência de mensagens. Exibem as ocorrências de execução. Melhores para a visualização geral do fluxo. Melhores para especificações de tempo-real e cenários complexos. Exibem relacionamentos, além das interações. Melhores para visualização de padrões de comunicação. Melhores para visualização de todos os efeitos de um dado objeto. Mais fáceis de serem utilizados em sessões de “brainstorming”. Sequence and communication diagrams express similar information, but show it in different ways. Communication diagrams emphasize the structural communication of a society of objects and show a clearer picture of the pattern of relationships and control that exist among the objects participating in a use case. Communication diagrams also show more structural information, such as the relationships among objects. Communication diagrams are better for understanding all the effects of a given object and for procedural design. Sequence diagrams show the explicit sequence of messages and are better for real-time specifications and complex scenarios. A sequence diagram includes chronological sequences but does not include object relationships. Sequence numbers are often omitted in sequence diagrams, in which the physical location of the arrow shows the relative sequence. On sequence diagrams, the time dimension is easier to read, the operations and parameters are easier to present, and the larger number of objects are easier to manage than in communication diagrams. Both sequence and communication diagrams allow you to capture semantics of the use-case flow of events. They help identify objects, classes, interactions, and responsibilities, as well as validate the architecture.

26 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Check that the students understand what was presented in the module. A. An interaction diagram shows an interaction consisting of a set of objects and their relationships, including the messages that may be dispatched among them. B. A sequence diagram describes a pattern of interaction among objects, arranged in a chronological order. A communication diagram shows how objects interact to perform a particular the behavior. C. A timing diagram is a time constraint view of messages involved in an interaction. An interaction overview diagram is a high level view of interactions combined into logic sequence. D. Like sequence diagrams, communication diagrams are used by designers to define and clarify the roles of the objects that perform a particular flow of events of a use case. Sequence diagrams and communication diagrams are also semantically equivalent. E. Communication diagrams show more structural information, such as the relationships among objects. A sequence diagram includes chronological sequences but does not include object relationships. Resumo Qual a proposta de um diagrama de interação? O que é um diagrama de seqüência? E um diagrama de comunicação? O que é um diagrama de tempo? E um diagrama geral de interação? Quais são as similaridades entre os diagramas de seqüência e de comunicação? Quais são as diferenças entre os diagramas de seqüência e de comunicação?

27 Dado: Produzir: Exercício
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Give the students the opportunity to draw their first sequence and communication diagram. Exercício Dado: Um conjunto de objetos, suas ligações e mensagens. Produzir: Um diagrama de seqüência. Um diagrama de mensagens. You are responsible for creating a sequence and communication diagram for the use case or use cases you are modeling. Remember, an interaction diagram should model one scenario in the use case. If you are going to model multiple scenarios, you’ll need to create an interaction diagram for each scenario. Refer to the following slides if needed. What Is a Sequence Diagram? slides 9-16 What Is a Communication Diagram? slides 18-22 Draw sequence and communication diagrams using the following data: The Prospective Buyer actor begins the sequence by requesting the Personal Planner Profile object (PPF) to maintain a profile. The PPF requests the Personal Planner Controller object (PPC) to maintain a profile. The PPC sends a message to the Buyer Record object asking it to find the planner record. The PPF then displays the planner record. The Prospective Buyer updates some information on the profile and asks the PPF to save the profile information. The PPF takes the new information and requests that the PPC save the profile information. The PPC asks the Buyer Record to update the record with the latest information that the actor has provided. The PPC asks the Customer Profile object to create a new profile for the system. Review your models and describe what the information says.

28 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Dúvidas?

29 Modelagem de Software Orientado a Objetos
PONTIFÍCIA UNIVERSIDADE CATÓLICA DE SÃO PAULO CURSO DE ESPECIALIZAÇÃO EM ENGENHARIA DE SOFTWARE Modelagem de Software Orientado a Objetos Modelagem de Software Orientado a Objetos Parte 2- Princípios de Modelagem UML Diagrama de Classes Prof. Maurício Nacib Pontuschka

30 Demonstrar como ler e interpretar um diagrama de classes.
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Introduce the objectives for this module to the students. Objetivos Descrever uma visão estática do sistema e mostrar como capturá-la em um modelo. Demonstrar como ler e interpretar um diagrama de classes. Modelar associações e agregações e mostrar como incluir o modelo em um diagrama de classes. Modelar generalizações em um diagrama de classes.

31 Relacionamento de Classes Associação Agregação Generalização
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The purpose of this section is to introduce, not teach everything about class diagrams. Remember, this is new to the students. Onde Estamos? Diagrama de Classes Relacionamento de Classes Associação Agregação Generalização

32 O que é um diagrama de classes?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Introduce class diagrams to the students. Interaction diagrams show the dynamic aspects of a system, while class diagrams show the static aspects of a system. O que é um diagrama de classes? Visão estática de um sistema CloseRegistrationForm + open() + close registration() Schedule - semester + commit() + select alternate() + remove offering() + level() + cancel() + get cost() + delete() + submit() + save() + any conflicts?() + create with offerings() + update with new selections() CloseRegistrationController + is registration open?() + close registration() Professor - name Student + get tuition() + add schedule() + get schedule() + delete schedule() + has pre-requisites() - employeeID : UniqueId A class diagram shows the existence of classes and their relationships in the logical design of a system. A class diagram may represent all or part of the class structure of a system. Class diagrams show the static structure of the model, in particular, the things that exist such as classes, their internal structure, and their relationships to other classes. Class diagrams do not show temporal information. The static view of a system primarily supports the functional requirements of a system. - hireDate - status - discipline - maxLoad + submitFinalGrade() + acceptCourseOffering() + setMaxLoad() + takeSabbatical() + teachClass()

33 Utilidade de um diagrama de classes
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Set the context for this module and present some reasons for using class diagrams. Class diagrams are not entity-relationship diagrams. They go one step further with behavior. The database schema may not always match 1:1 with the class diagram, but they should be fairly close. Utilidade de um diagrama de classes Ao modelar a visão estática de um sistema, o diagrama de classes é tipicamente utilizado de três formas, para modelar: o vocabulário de um sistema, colaborações, Esquema lógico de um banco de dados. Class diagrams allow you to model the vocabulary of your system when you determine the abstractions that are part of, or outside of, the boundaries of your system. Class diagrams specify these abstractions and their responsibilities. A collaboration is a grouping of classes and other elements that work together to provide a solution that is bigger than the sum of the elements in the collaboration. No class stands alone, but works in collaboration with other elements to carry out some sort of solution. Class diagrams are one way to model these collaborations. A database schema is similar to the blueprints for the conceptual design of a database. Many of the systems that you’ll design have persistent objects, which means that they have to be stored in a database for later retrieval. You can model schemas for these databases using class diagrams. The UML’s class diagrams are a superset of entity-relationship (E-R) diagrams. However, where typical E-R diagrams focus only on data, class diagrams take it one step further and allow the modeling of behavior, too. Behavior, modeled as operations, are generally turned into triggers or stored procedures on the database.

34 Exempo: Diagrama de Classes
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Provide an example of a class diagram. Ask: how many classes have you worked with on your largest project? Explain how difficult it can become to keep up with all of these classes. Offer examples from your own experience. Exempo: Diagrama de Classes Existe uma melhor forma de se organizar um diagrama de classes? RegistrationController LoginForm RegisterForCoursesForm Schedule CloseRegistrationForm CloseRegistrationController It’s not unusual for a system under development to contain hundreds, even thousands of different classes. Managing such large numbers generates its own problems. How can you organize classes and not lose the organization of the model? Professor Student Course CourseOffering CourseCatalogSystem BillingSystem

35 Revisão: O que é um pacote?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML A package is really a “virtual bag.” You can place just about anything inside of it that you like. Packages allow us to organize our models into pieces that make sense. They support the OO concepts of hierarchy and modularity. Revisão: O que é um pacote? Um mecanismo genárico para organização de elementos em grupos. Um elemento de modelo que pode conter outros elementos de modelo.. Um pacote pode ser utilizado para: Organizar um modelo sob desenvolvimento; Como unidade de gestão de configuração. University Artifacts A Package can be defined as: A general purpose mechanism for organizing elements into groups. (The Unified Modeling Language User Guide, Booch, 1999.) Models can have hundreds, even thousands, of model elements. The sheer number of these elements can quickly become overwhelming. It’s critical to group model elements into logical collections to keep the model manageable and readable. Packages are a generic mechanism for grouping elements into semantically related groups. A package contains classes that are needed by a number of different packages, but are treated as a “behavioral unit.” A package is simply a grouping mechanism. No semantics are defined for its instances. Thus, packages do not necessarily have a representation in implementation (except perhaps to represent a directory). In the UML, a package is represented as a tabbed folder. Package diagrams depict dependencies between packages and are now formalized in UML 2.

36 Exemplo: Pacote Registration
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Show the students how a package would look on a class diagram. Exemplo: Pacote Registration Registration CloseRegistrationForm CloseRegistrationController RegisterForCoursesForm RegistrationController These four classes - CloseRegistrationForm, RegisterForCoursesForm, CloseRegistrationController, and RegistrationController - have all been assigned to the Registration package because they are highly cohesive.

37 Relacionamento de Classes Associação Agregação Generalização
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The purpose of this section is to introduce, not teach everything about class diagrams. Remember, this is new to the students. Onde Estamos? Diagrama de Classes Relacionamento de Classes Associação Agregação Generalização

38 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Introduce the concept of association to the students. This is new and may pose trouble for some students. There are also dependency relationships. However, dependencies are beyond the scope of this course since they are contingent on parameter, local variable or global reference. These topics are discussed in the Object-Oriented Analysis and Design course. For the beginner, understanding associations is enough. Draw these examples on the board as objects to help students understand the concept. O que é uma associação? Relacionamento semântico entre dois ou mais classificadores que especifica conexões entre as suas instâncias. Um relacionamento estrutural que especifica que objetos de uma classe estão conectados aos da outra classe. An Association can be defined as: The semantic relationship between two or more classifiers that specifies connections among their instances. In other words, an association is a structural relationship that specifies that objects (instances of classes) of one thing are connected to objects of another thing. The way that you show these structural relationships between classes is through the use of associations. Associations are represented on class diagrams by a line connecting the associating classes. Data may flow in either direction or both directions across a link. Most associations are simple. That is, they exist between exactly two classes. They are drawn as solid paths connecting pairs of class symbols. Ternary relationships are also possible. Sometimes, a class has an association to itself. This does not always mean that an instance of that class has an association to itself. More often, it means that one instance of the class has associations to other instances of the same class. This example shows that a student object is related to a schedule object. The second example demonstrates how a course object can be related to another course object. Estudante Calendário Curso

39 Exemplo: Que associações você pode encontrar?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Have the students brainstorm what the class diagram looks like. One way to do this is to use the “whiteboard” to display the information that they find. Note: The reflexive message on the Schedule object does not mean that there is a reflexive association on the Schedule class. Also, the actor is not represented on the class diagram. The total number of associations that can be found on this slide are 5. The link between the actor and the Form is not an association and the reflexive message on Schedule does not indicate an association to self. . Exemplo: Que associações você pode encontrar? : CourseOffering : RegistrationController : Schedule : Student : PrimaryScheduleOfferingInfo 8: any conflicts?( ) : RegisterForCoursesForm 2: submit schedule( ) 4: submit( ) 3: save( ) 7: still open?( ) 9: add student(Schedule) 5: is selected?( ) 10: mark as enrolled in( ) 6: has pre-requisites(CourseOffering) 1: submit schedule( ) Using the information that you just learned, what do you think the class diagram representing this communication diagram looks like?

40 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Introduce the concept of multiplicity. O que é multiplicidade? Multiplicidade é o número de instâncias de uma classe qual se relaciona com UMA instância da outra classe. Para cada associação, existem duas decisões de multiplicidade a serem tomadas, uma para cada extremidade da associação. Para cada instância de Professor, muitas ofertas de cursos podem existir. Para cada instância de oferta de curso, podem haver um ou nenhum professor como instrutor. Multiplicity can be defined as: The number of instances one class relates to one instance of another class. For each role, you can specify the multiplicity of its class and how many objects of the class can be associated with one object of the other class. Multiplicity is indicated by a text expression on the role. The expression is a comma-separated list of integer ranges. It is important to remember that multiplicity is referring to instances of classes (objects) and their relationships. In this example, a Course Offering object may have either zero or one Professor object related to it. Conversely, a Professor object may have zero or more Course Offering objects related to it. Multiplicity must be defined on both ends of the association. - instrutor Professor Oferta de Curso 0..1 0..1 0..* 0..*

41 Indicadores de Multiplicidade
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Show the valid multiplicity indicators. The use of “N” instead of “*” is Booch, not UML (for example, the use of “0..N” and “N” is not UML). The multiplicity specified for a relationship is for all instances of that relationship, not simply for a particular use-case realization or for a particular point in time. Indicadores de Multiplicidade Não especificado Exatamente um 1 Zero ou mais 0..* Zero ou mais * Multiplicity is indicated by a text expression on the role. The expression is a comma-separated list of integer ranges. A range is indicated by an integer (the lower value), two dots, and an integer (the upper value). A single integer is a valid range, and the symbol “*” indicates "many.” That is, an asterisk “*” indicates an unlimited number of objects. The symbol “*”by itself is equivalent to “0..*” That is, it represents any number including none. This is the default value. Optional value has the multiplicity 0..1. Um ou mais 1..* Zero ou um (valor opcional) 0..1 Faixa específica 2..4 Múltiplas Faixas descontínuas 2, 4..6

42 Exemplo: Multiplicidade
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Provide the students with an opportunity to see how multiplicity can be interpreted from a class diagram. Here are the answers to the student notes questions. 1. There is an association relationship between each of the classes. RegisterForCoursesForm to RegistrationController has a lower and upper bound of 1. Schedule to CourseOffering is 0 (low) to 4 (high). CourseOffering to Schedule is 0 (low) to many (high). 2. A RegisterForCoursesForm instance is mandatory because it must be associated with exactly one instance of RegistrationController. 3. Zero to four. 4. One. 5. No, a schedule must be associated to one student. 6. For each RegisterForCoursesForm, there is one RegistrationController which has zero or one Schedule. Exemplo: Multiplicidade 1 1 RegisterForCoursesForm RegistrationController 1 1 0..1 0..1 Describe the following relationships between: RegisterForCoursesForm and RegistrationController; Schedule to CourseOffering; and CourseOffering to Schedule. What is the lower and upper bounds for these relationships? Which relationships are mandatory? What do the mandatory relationships tell you about the different classes? How many course offerings can appear on a Schedule? How many students are assigned to each Schedule? Can a Schedule exist without a student? How many schedules can be open on a RegisterForCoursesForm? 0..1 1 0..* Student Schedule CourseOffering 0..* 0..4

43 Relacionamento de Classes Associação Agregação Generalização
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The purpose of this section is to introduce, not teach everything about class diagrams. Remember, this is new to the students. Onde Estamos? Diagrama de Classes Relacionamento de Classes Associação Agregação Generalização

44 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Introduce the concept of aggregation to the students. Composition is not covered in this course. Composition is a stronger form of aggregation that indicates coincident lifetimes. O que é uma agregação? Uma forma especial de associação a qual modela um relacionamento parte-de entre a agregação (o todo) e suas partes. Uma agregação é um relacionamento “parte-de”. A multiplicidade é representada da mesma forma que em outras associações. An Aggregation can be defined as: A special form of association that models a whole-part relationship between an aggregate (the whole) and its parts. Aggregation is used to model a whole-part relationship between model elements. There are many examples of whole-part relationships: a Library contains Books, Departments are made up of Employees, a Computer is composed of a number of Devices. To model an aggregation, the aggregate (Department) has an aggregation association to its constituent parts (Employee). A hollow diamond is attached to the end of an association path on the side of the aggregate (the whole) to indicate aggregation. An aggregation relationship that has a multiplicity greater than one for the aggregate is called shared. Destroying the aggregate does not necessarily destroy the parts. By implication, a shared aggregation forms a graph or a tree with many roots. Shared aggregations are used when one instance is a part of two other instances. So, the same instance can participate in two different aggregations. Todo 1 Parte 0..1

45 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Give the students an opportunity to see how aggregation can be interpreted from a class diagram. Have the students answer each of the questions in the student notes. Here are the answers to the student notes questions. 1. The Schedule to Student instance is an example of an aggregation. 2. Schedule is a part of the Student aggregate (whole). 3. This relationship is an aggregate because it has a multiplicity greater than one. It models a whole-part relationship. Exemplo: Agregação 1 1 RegisterForCoursesForm RegistrationController 1 1 0..1 0..1 Which relationship is an aggregation? How would you read this aggregate relationship? Why is this relationship an aggregate? 0..1 1 0..* Student Schedule CourseOffering 0..* 0..4

46 Relacionamento de Classes Associação Agregação Generalização
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML The purpose of this section is to introduce, not teach everything about class diagrams. Remember, this is new to the students. Onde Estamos? Diagrama de Classes Relacionamento de Classes Associação Agregação Generalização

47 Revisão: O que é Generalização?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Generalization relationships are also permitted between packages. However, packages do not have semantics. Therefore, generalization between packages is not common. Generalization among subsystems is practical. According to Grady Booch: The terms “inheritance” and “generalization” are, practically speaking, interchangeable. The UML standard is to call the relationship “generalization,” so as not to confuse people with language-specific meanings of inheritance. To confuse matters more, some call this an “is-a” or a “kind of” relationship (especially those into conceptual modeling in the cognitive sciences). So, for most users, it’s fair to use either term. For power users, people who care about things like the UML metamodel and specifying formal semantics of the same, the relationship is called “generalization” and applying such a relationship between two classes, for example, results in the subclass inheriting the structure and operations of the superclass (inheritance is the mechanism). Revisão: O que é Generalização? Um relacionamento entre classes onde uma classe compartilha sua estrutura e/ou seu comportamento de uma ou mais classes. Define uma hierarquia de abstrações onde a subclasse herda elementos de uma ou mais superclasses. Herança simples Herança múltipla É um relacionamento “é-um”. Generalization can be defined as: A specialization/generalization relationship, in which objects of the specialized element (the child) are substitutable for objects of the generalized element (the parent). (The Unified Modeling Language User Guide, Booch, 1999.) The subclass may be used where the superclass is used, but not vice versa. The child inherits from the parent. Generalization is transitive. You can always test your generalization by applying the “is a kind of” rule. You should always be able to say that your specialized class “is a kind of” the parent class. The terms “generalization” and “inheritance” are generally interchangeable, but if you need to distinguish, generalization is the name of the relationship. Inheritance is the mechanism that the generalization relationship represents/models. Inheritance can be defined as: The mechanism by which more-specific elements incorporate the structure and behavior of more-general elements. (The Unified Modeling Language User Guide, Booch, 1999.) Single inheritance: The subclass inherits from only one superclass (has only one parent). Multiple inheritance: The subclass inherits from more than one superclass (has multiple parents).

48 Exemplo: Herança simples
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Demonstrate how generalization looks on a class diagram. This is the UML representation of generalization that was introduced earlier in the course. Exemplo: Herança simples Uma classe herda elementos de outra Ancestral Account - balance Superclasse (pai) - name - number + withdraw() + createStatement() The generalization is drawn from the subclass class to the superclass/parent class. The terms “ancestor” and “descendent” may be used instead of “superclass” and “subclass.” Relacionamento de generalização Subclasse (filha) Savings Checking Descendentes

49 Exemplo: Herança Múltipla
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Demonstrate how generalization looks on a class diagram. Some languages do not support multiple inheritance. This is the UML representation of generalization that was introduced earlier in the course. Exemplo: Herança Múltipla Uma classe pode ser herdeira de várias outras Voador Animal Herança Múltipla Multiple inheritance means that a class can inherit from several other classes. For example, Bird inherits from both FlyingThing and Animal. Multiple inheritance is conceptually straight forward and may be needed to model the real world accurately. However, there are potential implementation problems when you use multiple inheritance, and not all implementation languages support it. Thus, be judicious with your use of multiple inheritance. Use it only where it accurately describes the concept you are trying to model and reduces the complexity of your model. Be aware, however, that this representation probably needs to be adjusted in design and implementation. Generally, a class inherits from only one class. Avião Helicóptero Ave Lobo Cavalo Utilize herança múltipla somente se for necessário e sempre com muita atenção!

50 O que um diagrama de classes representa?
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML A. A class diagram shows the existence of classes and their relationships in the logical design of a system. Packages allow us to organize our models into pieces that make sense. An association is a structural relationship that specifies that objects (instances of classes) are connected to objects of a another. An aggregation is a special form of association that models a whole-part relationship between an aggregate (the whole) and its parts. Generalization is a relationship among classes where one class shares the structure and/or behavior of one or more classes. Associations are represented on class diagrams by a line connecting the associating classes. Data may flow in either direction or both directions across a link. Multiplicity is the number of instances one class relates to ONE instance of another class. For each role, you can specify the multiplicity of its class and how many objects of the class can be associated with one object of the other class. Revisão O que um diagrama de classes representa? Qual benefício os pacotes propiciam ao modelo? Defina associação, agregação e generalização. Como encontramos associações? O que é multilicidade? Quais informações a multiplicidade fornece ao modelador?

51 Dado: Desenhe: Exercício Um conjunto de classes e seus relacionamentos
Modelagem de Software Orientado a Objetos Princípios de Modelagem UML Provide the students with an opportunity to draw their first class diagram. Exercício Dado: Um conjunto de classes e seus relacionamentos Desenhe: Um diagrama de classes Document a class diagram using the following information: A class diagram containing the following classes: Personal Planner Profile, Personal Planner Controller, Customer Profile, and Buyer Record. Associations drawn using the following information: Each Personal Planner Profile object can be associated with up to one Personal Planner Controller object. Each Personal Planner Controller object must be related to one Personal Planner Profile. A Personal Planner Controller object can be associated with up to one Buyer Record and Customer Profile object. An instance of the Buyer Record class can be related to zero or one Personal Planner Controller. Zero or one Personal Planner Controller objects are associated with each Customer Profile instance.

52 Modelagem de Software Orientado a Objetos Princípios de Modelagem UML
Dúvidas?


Carregar ppt "Modelagem de Software Orientado a Objetos"

Apresentações semelhantes


Anúncios Google