Sequence diagram pattern visitor
1 / 111

Sequence Diagram & Pattern Visitor - PowerPoint PPT Presentation

  • Uploaded on

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.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Sequence Diagram & Pattern Visitor' - yorick

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Sequence diagram pattern visitor

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

  • Sequence Diagram

  • Sanaz Bonakdar

  • Behin Behdinian

  • Kate Dehbashi


  • 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


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

The basics
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.

Sequence diagram elements
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.


Found Message




  • 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


  • 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 Student

      class used in a lifeline whose instance

      name is freshman


  • 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

Figure 2
Figure 2

Figure 2: An example of messages being sent between objects

Figure 21
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.


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


Loops and conditional
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

Loops and conditional1
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.

Figure 8
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. 

Create sequence diagram in eclipse
Create Sequence Diagram in Eclipse

  • How to create Create Sequence Diagram in Eclipse ?

Sequence diagram1
Sequence Diagram

  • Synchronous and Asynchronous call

Synchronous call
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.


Asynchronous call
Asynchronous call

  • If a caller sends an asynchronous message, itcan 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)

Sequence diagram observations
Sequence Diagram Observations

  • UML sequence diagram represent behavior in terms of interactions.

  • They complement class diagrams, which represent structure.

  • Useful for finding participating objects.

Comparison with other diagrams
Comparison with other Diagrams

  • Sequence diagram

  • State diagram

  • Activity diagram

  • Communication diagram

  • Timing diagram

Sequence diagram2
Sequence diagram

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

State diagram
State diagram

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

Activity diagram
Activity diagram

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

Sequence diagram application
Sequence Diagram Application

Sequence diagrams are typically used to model

  • Usage scenario

  • The logic of method

  • The logic of Services

Sequence diagram application i
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.

Sequence diagram application i1
Sequence Diagram Application(I)

Fund available:


Withdraw cash

Insufficient fund:

Withdraw cash

Card Holder

Sequence diagram applications
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.

The logic of method
The Logic of Method








Eligibility Status


Sequence diagram application1
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).

Enroll in seminar use case


(vector of student object)

Enroll in seminar Use case


Persistance framework


Build SQL Select


Select statement

List of all potential matches

Result set

Student data structure

The logic of method1
The Logic of Method








Eligibility Status


Basic course of action
Basic course of action:

  • The student wants to enroll in a seminar.

  • The student inputs his name and student number into the system

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

  • The system displays the list of available seminars.

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

  • The system validates that the student is eligible to enroll in the seminar

  • The system validates that the seminar fits into the existing schedule of the student

  • The system calculates the fees for the seminar

  • The system displays the fees

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

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

  • The system enrolls the student in the seminar.


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.

Alternate course a
Alternate course A:

The student is not eligible to enroll in seminars

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

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

  • The use case ends.

Alternate course b
Alternate course B

The student does not have the prerequisites

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

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

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

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

Alternate course c
Alternate course C

The student decides not to enroll in an available seminar

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

  • The use case ends.

Sequence diagram4
Sequence Diagram

  • System Sequence Diagram


System sequence diagram ssd example
System Sequence Diagram (SSD) - Example


Online Shopping

Shopping in the store

System sequence diagram ssd actor
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

System sequence diagram ssd system events
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

System sequence diagram ssd system operation
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)


System sequence diagram ssd use case
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

System sequence diagram ssd use case cont
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.

System sequence diagram ssd use case example brief
System Sequence Diagram (SSD) – Use Case ExampleBrief

  • Brief

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

System sequence diagram ssd use case example casual
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.

System sequence diagram ssd use case example fully dressed
System Sequence Diagram (SSD) – Use Case Example Fully Dressed

  • Fully-dressed example: Process Sale

    Use case UC1: Process Sale

    Primary 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? …

System sequence diagram ssd use case fully dressed cont
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.

System sequence diagram ssd
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

System sequence diagram ssd1
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”

System sequence diagram ssd2
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

System sequence diagram ssd3
System Sequence Diagram (SSD)

  • Which senarions should have a SSD?

    • Main success senario

    • Frequent senario

    • Complex senario

System sequence diagram ssd4
System Sequence Diagram (SSD)

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

System sequence diagram ssd naming
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”

Inter system ssd
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

System sequence diagram ssd glossary
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

System sequence diagram ssd summary
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.


  • 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

  • Pattern visitor

    Pattern - Visitor

    Amee Joshi

    Monali Bhavsar


    • Problem

    • Motivation

    • Applications

    • Participants

    • Collaborations

    • Consequences

    • Implementation

    • Comparison with other patterns

    • Drawback

    Visitor pattern intent
    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.

    Visitor pattern problem when do you use the visitor pattern
    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.


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


    • 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

    Node class hierarchy
    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

    Problem with node class hierarchy
    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


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

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

    Applicability of visitor pattern
    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.

    Visitor pattern participants
    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.

    Visitor pattern participants1
    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.

  • Visitor pattern participants2
    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.


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

    Example continue
    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.

    Example continue1
    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().


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


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


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


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

    The visitor pattern implementation
    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

    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++

    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)

    Who is responsible for traversing the structure
    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

    Example customers application
    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.

    Example continue2
    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.

    Visitor pattern known uses
    Visitor Pattern Known Uses

    • Smalltalk-80 Compiler

    • IRIS Inventor Toolkit

    • X Consortium’s Fresco ApplicationToolkit

    • Bistro Programming Language Compiler

    Sequence diagram pattern visitor
    Visitors and IteratorsThe iterator pattern and Visitor pattern has the same benefit. used to traverse object structures.



    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.

    • 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

    Visitors and composites
    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.


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

    Visitor pattern using reflection
    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.

    Java example
    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.


    • 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