111
Sequence Diagram & Pattern Visitor California State University , Los Angeles Dr. Jiang Guo Fall 2010 Presented by : Sanaz Bonakdar Behin Behdinian Kate Dehbashi Amee Joshi Monali Bhavsar

Sequence Diagram & Pattern Visitor

  • Upload
    yorick

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

Sequence Diagram & Pattern Visitor. California State University , Los Angeles Dr. Jiang Guo Fall 2010 Presented by : Sanaz Bonakdar Behin Behdinian Kate Dehbashi Amee Joshi Monali Bhavsar. Sequence Diagram. Sequence Diagram Sanaz Bonakdar Behin Behdinian Kate Dehbashi. Outline. - PowerPoint PPT Presentation

Citation preview

Page 1: Sequence Diagram & Pattern Visitor

Sequence Diagram&

Pattern VisitorCalifornia State University , Los Angeles

Dr. Jiang Guo Fall 2010

Presented by :Sanaz BonakdarBehin BehdinianKate Dehbashi

Amee JoshiMonali Bhavsar

Page 2: Sequence Diagram & Pattern Visitor

Sequence Diagram

Sequence Diagram Sanaz Bonakdar

Behin Behdinian

Kate Dehbashi

Page 3: Sequence Diagram & Pattern Visitor

Outline

Sequence Diagram Elements Loops and Conditional Video example on creating SD in Eclipse Synchronous and Asynchronous call Sequence Diagram Application The Logic of Method System Sequence Diagram

Actor System Events System Operation Use Case

Page 4: Sequence Diagram & Pattern Visitor

Introduction

The sequence diagram is one of the interaction diagrams

Shows the interactions between objects in the sequential order

It captures the behavior of a single scenario

Shows a number of objects and the messages that are passed between these objects within the use case

Its useful in documenting how a future system should behave

It can be used in the transition from requirements expressed as use cases to the next and more formal level of refinement.

Page 5: Sequence Diagram & Pattern Visitor

The Basics

The main purpose of a sequence diagram is to define event sequences that result in some desired outcome.

The focus is less on messages themselves and more on the order in which messages occur

The diagram conveys this information along the horizontal and vertical dimensions

The vertical dimension shows, top down, the time sequence of messages/calls as they occur

The horizontal dimension shows, left to right, the object instances that the messages are sent to.

Page 6: Sequence Diagram & Pattern Visitor

Sequence Diagram Elements

Page 7: Sequence Diagram & Pattern Visitor

Sequence Diagram Elements

Columns = Object Arrows = messages Narrow rectangles =

activations Dashed lines = lifelines Column fuller syntax name :

Class Both the name and the class

name are optional, but must keep the colon if use the class.

Called found message= The first message doesn’t have a participant. Lifeline

Found Message

Message

Activation

Participant

Page 8: Sequence Diagram & Pattern Visitor

Frame

Frame The frame element is used as a basis for many other

diagram elements in UML 2 It provides a consistent place for a diagram's label The frame element is optional in UML diagrams The format of using Frame : Diagram Type Diagram

Name

Page 9: Sequence Diagram & Pattern Visitor

Lifelines

Lifelines Lifeline notation elements are placed across the top of the

diagram Lifelines are drawn as a box with a dashed line descending

from the center of the bottom edge. The lifeline's name is placed inside the box.

Lifelines represent either roles or object instances that participate in the sequence being modeled .

The UML standard for naming a lifeline follows the format of : Instance Name : Class Name

Figure 1: An example of the Studentclass used in a lifeline whose instance name is freshman

Page 10: Sequence Diagram & Pattern Visitor

Message

The first message of a sequence diagram always starts at the top and is typically located on the left side of the diagram

Subsequent messages are then added to the diagram slightly lower then the previous message.

Solid arrowhead (synchronous call operation ) or stick arrowhead (asynchronous signal ):To show an object (i.e., lifeline) sending a message to another object

The message/method name is placed above the arrowed line .

Dotted line is return message and its optional

Page 11: Sequence Diagram & Pattern Visitor

Figure 2

Figure 2: An example of messages being sent between objects

Page 12: Sequence Diagram & Pattern Visitor

Figure 2

In the example in Figure 2, the analyst object makes a call to the system object which is an instance of the ReportingSystem class by getAvailableReports method.

The system object then calls the getSecurityClearance method with the argument of userId on the secSystem object

The secSystem object returns userClearance to the system object when the getSecurityClearance method is called

The system object returns availableReports when the getAvailableReports method is called.

Page 13: Sequence Diagram & Pattern Visitor

Guard

Guards are used throughout UML diagrams to control flow

We placed the guard element above the message line being guarded and in front of the message name.

Guard

Page 14: Sequence Diagram & Pattern Visitor

Loops and Conditional

Page 15: Sequence Diagram & Pattern Visitor

Loops And Conditional

Sequence diagrams also can show the looping and conditional behavior.

Treat sequence diagrams as a visualization of how objects interact rather than as a way of modeling control logic.

Both loops and conditionals use interaction frames ,which are ways of marking off a piece of a sequence diagram.

Frames consist of some region of a sequence diagrams that is divided into one or more fragments.

Each frame has an operators Each fragment may have a guard

Page 16: Sequence Diagram & Pattern Visitor

Loops And Conditional

To show a loop, we use the loop operator with a single fragment and put the basis of the interaction in the guard

alt : For conditional logic, we can use an alt operator and put a condition on each fragment. Only the fragment whose guard is true will execute. (classic "if then else" logic )

opt : The option combination fragment is used to model a sequence that, given a certain condition, will occur; otherwise, the sequence does not occur. An option is used to model a simple "if then" statement

Other operators: par : indicates that the associated interaction fragments are

executed in parallel region: A critical region takes precedence over any other

enclosing fragments and does not allow other traces on any lifeline contained within the fragment to be executing at the same time

ref : refers to an interaction defined on another diagram.

Page 17: Sequence Diagram & Pattern Visitor

Figure 5 : Opt (“if-then”)

Page 18: Sequence Diagram & Pattern Visitor

Figure 6 : Alt (“if-else-then”)

Page 19: Sequence Diagram & Pattern Visitor

Figure 7 : Par

Page 20: Sequence Diagram & Pattern Visitor

Figure 8 :Loop

Page 21: Sequence Diagram & Pattern Visitor

Figure 8

Figure 8 indicate looping logic.  One way is to show a frame with the label loop and a constraint indicating what is being looped through, such as for each seminar . 

Figure8 includes an asynchronous message, the message to the system printer which has the partial arrowhead.  An asynchronous message is one where the sender doesn’t wait for the result of the message, instead it processes the result when and if it ever comes back.

Up until this point all other messages have been synchronous, messages where the sender waits for the result before continuing on. 

Page 22: Sequence Diagram & Pattern Visitor

Create Sequence Diagram in Eclipse

How to create Create Sequence Diagram in Eclipse ?

Page 23: Sequence Diagram & Pattern Visitor

Sequence Diagram

Synchronous and Asynchronous call

Page 24: Sequence Diagram & Pattern Visitor

Synchronous call

If a caller sends a synchronous message, it must wait until the message is done,

A message that is sent synchronously assumes that the receiver is ready and listening and the caller waits for the completion of the operation and the return. It does not continue with the next steps in its execution until the receipt

of a return.

-invoking a subroutine.

-ATM

Page 25: Sequence Diagram & Pattern Visitor

Asynchronous call

If a caller sends an asynchronous message, it can continue processing and doesn’t have to wait for response.

Asynchronous calls can be found in multithreaded applications and in message oriented middleware.

Asynchronous gives better responsiveness and reduces the temporal coupling but is harder to debug.(Temporal coupling refers to the degree to which the sending and handling of a

message are connected in time)

Page 26: Sequence Diagram & Pattern Visitor

Sequence Diagram Observations

UML sequence diagram represent behavior in terms of interactions.

They complement class diagrams, which represent structure.

Useful for finding participating objects.

Page 27: Sequence Diagram & Pattern Visitor

Comparison with other Diagrams

Sequence diagram

State diagram

Activity diagram

Communication diagram

Timing diagram

Page 28: Sequence Diagram & Pattern Visitor

Sequence diagram

Use sequence diagrams when we want to look at the behavior of several objects within a single use case.

Page 29: Sequence Diagram & Pattern Visitor

State diagram

Use state diagrams when we want to look at the behavior of a single object across many use cases.

Page 30: Sequence Diagram & Pattern Visitor

Activity diagram

Use activity diagrams when we want to look at the behavior across many use cases or many threads.

Page 31: Sequence Diagram & Pattern Visitor

Sequence Diagram Application

Sequence diagrams are typically used to model

Usage scenario

The logic of method

The logic of Services

Page 32: Sequence Diagram & Pattern Visitor

Sequence Diagram Application(I)

Usage Scenarios. A usage scenario is a description of a potential way your system is used.

The logic of usage scenario may be part of a use case, perhaps an alternate course. It may also be one entire pass through a use case, such as the logic described by the basic course of action or a portion of the basic course of action, plus one or more alternate scenarios. The logic of a usage scenario may also be a pass through the logic contained in several use cases.

Page 33: Sequence Diagram & Pattern Visitor

Sequence Diagram Application(I)

Card Holder

Page 34: Sequence Diagram & Pattern Visitor

Sequence Diagram Applications

The logic of methods Sequence diagrams

Can be used to explore the logic of a complex operation, function, or procedure. One way to think of sequence diagrams, particularly highly detailed diagrams, is as visual object code.

Page 35: Sequence Diagram & Pattern Visitor

The Logic of Method

Eligibility StatusseminarHistory

enrollStudent(aStudent)

getSeminarHistory()

enrollmentStatus

isStudentEligible(aStudent)

Page 36: Sequence Diagram & Pattern Visitor

Sequence Diagram Application

The Logic of Services

A service is effectively a high-level method, often one that can be invoked by a wide variety of clients. This includes web-services as well as business transactions implemented by a variety of technologies such as CORBA-Compliant Object Request Brokers(ORBs).

Page 37: Sequence Diagram & Pattern Visitor

Enroll in seminar Use case

student Persistance framework

Exsist(name,address,phone)

Search(student,name,address,phone)

Build S

QL S

elect

Select statement

DB

Result set

Student data structure

List of all potential matches

(vector of student object)

Page 38: Sequence Diagram & Pattern Visitor

The Logic of Method

Eligibility StatusseminarHistory

enrollStudent(aStudent)

getSeminarHistory()

enrollmentStatus

isStudentEligible(aStudent)

Page 39: Sequence Diagram & Pattern Visitor

Sequence Diagram

Page 40: Sequence Diagram & Pattern Visitor

Basic course of action:

1. The student wants to enroll in a seminar.

2. The student inputs his name and student number into the system

3. The system verifies that the student is eligible to enroll in seminars

4. The system displays the list of available seminars.

5. The student indicates the seminar in which he wants to enroll.

6. The system validates that the student is eligible to enroll in the seminar7. The system validates that the seminar fits into the existing schedule of the student

8. The system calculates the fees for the seminar

9. The system displays the fees

10. The system asks the student whether he still wants to enroll in the seminar.

11. The student indicates that he wants to enroll in the seminar.

12. The system enrolls the student in the seminar.

Page 41: Sequence Diagram & Pattern Visitor

Continue..

13. The system informs the student the enrollment was successful

14. The system bills the student for the seminar

15. The system asks the student if he wants a printed statement of the enrollment.

16. The student indicates that he does want a printed statement.

17. The system prints the enrollment statement

18. The use case ends when the student takes the printed statement.

Page 42: Sequence Diagram & Pattern Visitor

Alternate course A:

The student is not eligible to enroll in seminars

1. The system determines the student is not eligible to enroll in seminars.

2. The system informs the student he is not eligible to enroll.

3. The use case ends.

Page 43: Sequence Diagram & Pattern Visitor

Alternate course B

The student does not have the prerequisites

1. The system determines that the student is not eligible to enroll in the seminar he has chosen.

2. The system informs the student that he does not have the prerequisites.

3. The system informs the student of the prerequisites he needs.

4. The use case continues at Step 4 in the basic course of action.

Page 44: Sequence Diagram & Pattern Visitor

Alternate course C

The student decides not to enroll in an available seminar

1. The student views the list of seminars and doesn't see one in which he wants to enroll.

2. The use case ends.

Page 45: Sequence Diagram & Pattern Visitor

Sequence Diagram System Sequence Diagram

(SSD)

Page 46: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) - Example

Example Online Shopping Shopping in the store

Page 47: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) - Actor

Actor Specifies a role played by a user or any other

system that interacts with the system Generates events to a system, requesting some

operation in response Actors may represent roles played by human users,

external hardware, or other subjects UML 2 does not permit associations between Actors

Page 48: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – System Events

System Event External event Generated by an actor Directly stimulates the system To identify system events, it is necessary to be clear

on the choice of system boundry Example: customer chooses an

item for purchase (ProductID, amount)

Item#456464646 Qty.1

Page 49: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – System Operation

System operation Operation of the system Executes in response to a

system event

Example: System generates an

invoice (inv#,description,total amount)

Inv#6354254765

Page 50: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case

Use Case Description of a system’s behavior as it responds to a

request that originates from outside of that system “Who" can do "what" with the system Suggests how actors interact with the system Use cases treat the system as a black box Should be constructed by business domain

knowledgeable people A use case may show one or more (more commonly

more…) use case scenarios

Page 51: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case Cont.

Uses cases may be written in three formality types Brief

One-paragraph summary Usually of the main success scenario

Casual Informal paragraph format Alternate senarios

Fully dressed All steps and variations are written in detail.

Page 52: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case Example

Brief

Brief A customer arrives at a checkout with items to

return. The cashier uses thePOS system to record each returned item…

Page 53: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case Example

Casual

Informal Paragraph Format Main success scenario:

A customer arrives at a checkout with items to return. The cashier uses thePOS system to record each returned item…

Alternate scenarios: If the return authorization is rejected due to an

expired receipt, notify the cashier and suggest return for store credit only.

Page 54: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case Example

Fully Dressed

Fully-dressed example: Process Sale

Use case UC1: Process SalePrimary Actor: Cashier

Stakeholders and Interests:

Cashier: Wants accurate and fast entry, no payment errors, …

Salesperson: Wants sales commissions updated.

Preconditions: Cashier is identified and authenticated.

Success Guarantee (Postconditions):

Sale is saved. Tax correctly calculated…

Main success scenario (or basic flow): [see next slide]

Extensions (or alternative flows): [see next slide]

Special requirements: Touch screen UI, …

Technology and Data Variations List:

Identifier entered by bar code scanner,…

Open issues: What are the tax law variations? …

Page 55: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) – Use Case

Fully Dressed Cont.

Main success scenario (or basic flow):The Customer arrives at a POS checkout with items to purchase.

The cashier records the identifier for each item. If there is more than

one of the same item, the Cashier can enter the quantity as well.

The system determines the item price and adds the item information to

the running sales transaction. The description and the price of the current

item are presented.

On completion of item entry, the Cashier indicates to the POS system

that item entry is complete.

The System calculates and presents the sale total.

The Cashier tells the customer the total.

The Customer gives a cash payment (“cash tendered”) possibly greater

than the sale total.

Extensions (or alternative flows):If invalid identifier entered. Indicate error.

If customer didn’t have enough cash, cancel sales transaction.

Page 56: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD)

What is it? Sequence diagram Created for a particular senario of a use case

One diagram one senarion Illustrates

Events from actors to the system External response of the system

Should specify and show the following: External actors Messages (methods) invoked by these actors system events Return values associated with previous messages created by

the system system operations Indication of any loops or iteration area

Page 57: Sequence Diagram & Pattern Visitor
Page 58: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD)

Why is it created? Before procedeeing to a logical design of how a software

application will work, it is useful to define and investigate its behavior as a black box

In a black box, system is viewed solely in terms of input/output without any knowledge of its internal workings

Describing “what system does” without explaining “how it does it” One part of that description is a SSD

Other parts include “use cases” and “system contracts”

Page 59: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD)

When it is created? During analysis phase of the development process It is desirable to isolate and illustrare the operations that

an actor requests of a system. Why? Because they are the important part of analyzing system

behavior It depends on

The creation of the use cases

Page 60: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD)

Which senarions should have a SSD? Main success senario Frequent senario Complex senario

Page 61: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD)

SSD if often accompanied by a textual description of the senario to the left of the diagram

Page 62: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) - Naming

How to name system events and operations System events should be expressed at the level of intention To improve clarity, start the name of a system event with

a verb enterItem(itemID) instead of scan(itemID)

Captures the intention Respects design choices regarding the input device used to

capture system event Keep the system response at an abstract level

“Description, total” instead of “descrition and total”

Page 63: Sequence Diagram & Pattern Visitor

Inter-System SSD

SSDs can also be used to Illustrates collaboration between systems

Example: adding support for third-party external systems

SSDs should be updated to reflect at least some of the inter-system collaborations

Tax calculator Credit authorization

Page 64: Sequence Diagram & Pattern Visitor
Page 65: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) - Glossary

What information to be placed in glossory? SSD elements are terse Details and proper explanation Example

“Change due, receipt” Glossary:

Sample receipt Detailed content

Page 66: Sequence Diagram & Pattern Visitor

System Sequence Diagram (SSD) - Summary

A system sequence diagram is a picture that shows, for one particular scenario of a use case, the events that external actors generate, their order, and inter-system events. All systems are treated as a black box; the emphasis of the diagram is events that cross the system boundary from actors to systems.

Page 67: Sequence Diagram & Pattern Visitor

Conclusion

Sequence Diagram Advantages Clearly show

The sequence of events When objects are created and destroyed Concurrent operations

Sequence Diagram Disadvantages Take up a lot of space Do not present the inter relationships between the

collaborating objects very well

Do not create SSDs for all senarios

Page 68: Sequence Diagram & Pattern Visitor

Pattern - Visitor

Amee Joshi

Monali Bhavsar

Page 69: Sequence Diagram & Pattern Visitor

Outline

Problem

Motivation

Applications

Participants

Collaborations

Consequences

Implementation

Comparison with other patterns

Drawback

Page 70: Sequence Diagram & Pattern Visitor

Introduction

Creational Patterns

Singleton

Abstract Factory

Factory Method

Prototype

Builder

Structural Patterns

Composite

Façade

Proxy

Flyweight• Adapter• Bridge• Decorator

Behavioral Patterns

Chain of Responsibility

Command

Interpreter Iterator

Mediator

Memento

Observer

State

Strategy

Template Method

Visitor

Page 71: Sequence Diagram & Pattern Visitor

Visitor Pattern - Intent

Represent an operation to be performed on the elements of an object structure.

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Page 72: Sequence Diagram & Pattern Visitor

Visitor Pattern: ProblemWhen do you use the visitor Pattern?

Many distinct and unrelated operations need to be performed on objects in an object structure and you want to avoid “polluting” their classes with these operations

The classes defining the object structure rarely change but you often want to define new operations over the structure.

Page 73: Sequence Diagram & Pattern Visitor

Motivation

Consider a compiler that parses a program and represents the parsed program as an abstract syntax tree (AST). The AST has many different kinds of nodes, such as Assignment, Variable Reference, and Arithmetic Expression nodes.

One option: place all of these operations in the nodes of the AST.

Page 74: Sequence Diagram & Pattern Visitor

Motivation

Operations that one would like to perform on the AST include: Checking that all variables are defined Checking for variables being assigned before

they are used Type checking Code generation Pretty printing/formatting

Page 75: Sequence Diagram & Pattern Visitor

Node class hierarchy

These operations may need to treat each type of node differently

One way to do this is to define each operation in the specific node class

Page 76: Sequence Diagram & Pattern Visitor

Problem with Node class hierarchy

Distributing operations across Node classes leads to a system that’s hard to understand, maintain and change.

It’s confusing to have type-checking code in the same class with code to perform pretty printing.

Also, adding a new operation, e.g. data flow analysis, requires recompiling all of the classes

Page 77: Sequence Diagram & Pattern Visitor

Visitor

Allows us to separate Node classes from operations “on” Node classes

Allows each new operation to be added separately, without changing Node class!

Page 78: Sequence Diagram & Pattern Visitor

Nodes “accept” visitors

Page 79: Sequence Diagram & Pattern Visitor

Visitor for Nodes

Page 80: Sequence Diagram & Pattern Visitor

Applicability of Visitor Pattern

Use the Visitor pattern when An object structure contains many classes of

objects with different interfaces, and you want to perform operations on these objects that depend on their concrete classes.

Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class.

The classes defining the object structure rarely change, but you often want to define new operations over the structure.

Page 81: Sequence Diagram & Pattern Visitor

Visitor Pattern- Participants

Context(Visitor): Declares a Visit operation for each class of

ConcreteElement in the object structure. The operation's name and signature identifies the

class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the element directly through its particular interface.

ConcreteVisitor Implements each operation declared by Visitor. Each

operation implements a fragment of the algorithm defined for the corresponding class of object in the structure.

Page 82: Sequence Diagram & Pattern Visitor

Visitor Pattern- Participants

ConcreteVisitor provides the context for the algorithm and stores its local state.

This state often accumulates results during the traversal of the structure.

Element Defines an Accept operation that takes a visitor

as an argument.

ConcreteElement and/or ConcreteComposite Implements an Accept operation that takes a

visitor as an argument.

Page 83: Sequence Diagram & Pattern Visitor

Visitor Pattern- Participants

ObjectStructure Can enumerate its elements. May provide a high-level interface to allow

the visitor to visit its elements. May either be a composite or a collection

such as a list or a set.

Page 84: Sequence Diagram & Pattern Visitor

Structure of Visitor Pattern

Page 85: Sequence Diagram & Pattern Visitor

Example

This pattern can be observed in the operation of a taxi company. When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the customer. Upon entering the taxi the customer, or Visitor, is no longer in control of his or her own transportation, the taxi (driver) is.

Page 86: Sequence Diagram & Pattern Visitor

Example- continue

Confirm that the current hierarchy (known as the Element hierarchy) will be fairly stable and that the public interface of these classes is sufficient for the access the Visitor classes will require. If these conditions are not met, then the Visitor pattern is not a good match.

Create a Visitor base class with a visit(ElementXxx) method for each Element derived type.

Add an accept(Visitor) method to the Element hierarchy. The implementation in each Element derived class is always the same – accept( Visitor v ) { v.visit( this ); }. Because of cyclic dependencies, the declaration of the Element and Visitor classes will need to be interleaved.

Page 87: Sequence Diagram & Pattern Visitor

Example- continue

The Element hierarchy is coupled only to the Visitor base class, but the Visitor hierarchy is coupled to each Element derived class. If the stability of the Element hierarchy is low, and the stability of the Visitor hierarchy is high; consider swapping the ‘roles’ of the two hierarchies.

Create a Visitor derived class for each “operation” to be performed on Element objects. visit() implementations will rely on the Element’s public interface.

The client creates Visitor objects and passes each to Element objects by calling accept().

Page 88: Sequence Diagram & Pattern Visitor

Collaborations

A clients that uses the visitor pattern must create a ConcreteVisitor object and then traverse the object structure visiting each element with the visitor.

When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an argument to this operation.

Page 89: Sequence Diagram & Pattern Visitor

Collaborations

Page 90: Sequence Diagram & Pattern Visitor

Consequences

Benefits: Makes adding new operations is easy

Add new operation subclass with a method for each concrete element class is easier than modifying every element class. A new operation is defined by adding a new visitor.

Gathers related operations and separates unrelated ones Related behavior is localized in the visitor and not

spread over the classes defining the object structure.

Unrelated sets of behavior are partitioned in their own visitor subclasses.

Page 91: Sequence Diagram & Pattern Visitor

Consequences

Benefits: Accumulating States:

Visitor can accumulate state rather than pass it a parameters

Visitors can accumulate state as they visit each element in the object structure. Without a visitor, this state would have to be passed as extra arguments to the operations that perform the traversal.

Allows visiting across class hierarchies: An iterator can also visit the elements of an object

structure as it traverses them and call operations on them but all elements of the object structure then need to have a common parent. Visitor does not have this restriction.

Page 92: Sequence Diagram & Pattern Visitor

Consequences

Liabilities Adding new ConcreteElement classes is hard:

Must add a new method to each ConcreteVisitor subclass Each new ConcreteElement gives rise to a new abstract

operation on Visitor and a corresponding implementation in every ConcreteVisitor class.

Breaking encapsulation: Visitor’s approach assumes that the ConcreteElement

interface is powerful enough to allow the visitors to do their job.

As a result the pattern often forces to provide public operations that access an element‘s internal state, which may compromise its encapsulation.

Page 93: Sequence Diagram & Pattern Visitor

The Visitor Pattern Implementation

Double Dispatch The key to visitor is a double dispatch. The meaning of the accept operation

depends on the visitor & on the element languages that support double dispatch(CLOS) can do without this pattern.

The Visitor pattern allows you to add operations to classes without changing them using a technique called double-dispatch

Page 94: Sequence Diagram & Pattern Visitor

Single-Dispatch

The actual method invoked depends on the name of the request (method signature) and the type of the receiver object

For example, calling foo() on a object of Type X, invokes the foo() methodof X

The actual underlying type will be discovered through polymorphism

This is the standard technique used in languages like Java and C++

Page 95: Sequence Diagram & Pattern Visitor

Double-Dispatch

The actual method invoked depends on the name of the request and the types of two receivers

For example, consider an object of type Visitor1 calling accept(Visitor1) on an object of Type ElementA: The Visitor1 object dispatches a call to the accept(Visitor) method

of ElementA. The accept(Visitor) method of ElementA dispatches a call back to

the visitor (Visitor1), invoking the visit(ElementA) method of Visitor1 and passing itself as an argument.

This round trip effectively picks up the right type of Element, ensuring that the correct visit() method of the Visitor object is called.

Effectively, then, the method invoked depends on the request name (accept(Visitor)), the type of the Element object (ElementA) and the type of the Visitor object (Visitor1)

Page 96: Sequence Diagram & Pattern Visitor

Who is responsible for traversing the structure?

Responsibility of traversal can be with: The Object Structure

define operation that performs traversal while applying visitor object to each component

The Visitor Must replicate traversal code in each concrete visitor. Visitor is advisable when a particular complex traversal is

needed. For example, one that depends on the outcome of the

operation otherwise it I not advisable because a lot of traversal code will be duplicated in each concrete visitor for each aggregate concrete element

A separate Iterator object. Iterator sends message to visitor with current element as

argument

Page 97: Sequence Diagram & Pattern Visitor

Example - Customers Application.

We want to create a reporting module in our application to make statistics about a group of customers. The statistics should made very detailed so all the data related to the customer must be parsed. All the entities involved in this hierarchy must accept a visitor so the CustomerGroup, Customer, Order and Item are visitable objects.

Page 98: Sequence Diagram & Pattern Visitor
Page 99: Sequence Diagram & Pattern Visitor

Example- continue

In the example we can see the following actors:

IVisitor and IVisitable interfaces

CustomerGroup, Customer, Order and Item are all visitable classes. A CustomerGroup represents a group of customers, each Customer can have one or more orders and each order can have one ore more Items.

GeneralReport is a visitor class and implements the IVisitor interface.

Page 100: Sequence Diagram & Pattern Visitor

Visitor Pattern Known Uses

Smalltalk-80 Compiler

IRIS Inventor Toolkit

X Consortium’s Fresco ApplicationToolkit

Bistro Programming Language Compiler

Page 101: Sequence Diagram & Pattern Visitor

Visitors and IteratorsThe iterator pattern and Visitor pattern has the same benefit.

used to traverse object structures.

Visitors The visitor pattern can be

used on complex structure such as hierarchical structures or composite structures. In this case the accept

method of a complex object should call the accept method of all the child objects.

The visitor defines the operations that should be performed

Iterators Iterator is intended to be

used on collections. Usually collections contain objects of the same type.

The iterator is used by the client to iterate through the objects form a collection and the operations are defined by the client itself.

Page 102: Sequence Diagram & Pattern Visitor

Visitors and Composites

The visitor pattern can be used in addition with the composite pattern.

The object structure can be a composite structure.

In this case in the implementation of the accept method of the composite object the accept methods of the component object has to be invoked.

Interpreter- distribute code over class hierarchy

Visitor- centralize code in single class.

Page 103: Sequence Diagram & Pattern Visitor

Drawback

If a new visitable object is added to the framework structure all the implemented visitors need to be modified.

The separation of visitors and visitable is only in one sense: visitors depend of visitable objects while visitable are not dependent of visitors.

Part of the dependency problems can be solved by using Reflection with a performance cost.

Page 104: Sequence Diagram & Pattern Visitor

Visitor Pattern using Reflection

Reflection can be used to overcome the main drawback of the visitor pattern.

When the standard implementation of visitor pattern is used the method to invoke is determined at runtime.

Reflection is the mechanism used to determine the method to be called at compile-time.

This way the visitable object will use the same code in the accept method. This code can be moved in an abstraction so the IVisitable interface will be transformed to an advanced class.

Page 105: Sequence Diagram & Pattern Visitor

Java Example

The following example is in the Java programming language, and shows how the contents of a tree of nodes (in this case describing the components of a car) can be printed. Instead of creating "print" methods for each subclass (Wheel, Engine, Body, and Car), a single class (CarElementPrintVisitor) performs the required printing action. Because different subclasses require slightly different actions to print properly, CarElementDoVisitor dispatches actions based on the class of the argument passed to it.

Page 106: Sequence Diagram & Pattern Visitor

Example - continue

Page 107: Sequence Diagram & Pattern Visitor

Java Source code

Page 108: Sequence Diagram & Pattern Visitor

Continue

Page 109: Sequence Diagram & Pattern Visitor

Continue

Page 110: Sequence Diagram & Pattern Visitor

Refrences

Applying UML and Patterns, Larman c., second edition

Designing Scenarios: Making the Case for a Use Case Framework, Wirfs-Brock R., Nov/Dec 1993 issue of “The Smalltalk Report” ,Vol.3, No. 3

http://www.ibm.com/developerworks/rational/library/3101.html

www.Wikipedia.com

http://www.tracemodeler.com/articles/ a_quick_introduction_to_uml_sequence_diagrams/

http://www.zicomi.com/combinedFragmentCriticalRegion.jsp

http://en.wikipedia.org/wiki/Visitor_pattern

http://sourcemaking.com/design_patterns/visitor

http://www.csee.umkc.edu/~leeyu/class/CS590L-04/Presentation/Visitor.pdf

Page 111: Sequence Diagram & Pattern Visitor

Thank you