Sequence_Diagram_Pattern_Visitor_cs537_Final

advertisement
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
S
Sequence Diagram
S Sequence Diagram
S Sanaz Bonakdar
S Behin Behdinian
S Kate Dehbashi
Outline
S Sequence Diagram Elements
S Loops and Conditional
S Video example on creating SD in Eclipse
S Synchronous and Asynchronous call
S Sequence Diagram Application
S The Logic of Method
S System Sequence Diagram
S Actor
S System Events
S System Operation
S Use Case
Introduction
S The sequence diagram is one of the interaction diagrams
S Shows the interactions between objects in the sequential order
S It captures the behavior of a single scenario
S Shows a number of objects and the messages that are passed
between these objects within the use case
S Its useful in documenting how a future system should behave
S It can be used in the transition from requirements expressed as
use cases to the next and more formal level of refinement.
The Basics
S The main purpose of a sequence diagram is to define event
sequences that result in some desired outcome.
S The focus is less on messages themselves and more on the
order in which messages occur
S The diagram conveys this information along the horizontal
and vertical dimensions
S The vertical dimension shows, top down, the time sequence
of messages/calls as they occur
S The horizontal dimension shows, left to right, the object
instances that the messages are sent to.
SSequence 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.
S Called found message= The first
message doesn’t have a participant.
Participant
S
S
S
S
S
S
Activation
Found Message
Message
Lifeline
Frame
S Frame
S The frame element is used as a basis for many other diagram
elements in UML 2
S It provides a consistent place for a diagram's label
S The frame element is optional in UML diagrams
S The format of using Frame : Diagram Type Diagram Name
Lifelines
S Lifelines
S Lifeline notation elements are placed across the top of the diagram
S 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.
S Lifelines represent either roles or object instances that participate in the
sequence being modeled .
S The UML standard for naming a lifeline follows the format of :
S Instance Name : Class Name
Figure 1: An example of the Student
class used in a lifeline whose instance
name is freshman
Message
S The first message of a sequence diagram always starts at the
top and is typically located on the left side of the diagram
S Subsequent messages are then added to the diagram slightly
lower then the previous message.
S Solid arrowhead (synchronous call operation ) or stick
arrowhead (asynchronous signal ):To show an object (i.e.,
lifeline) sending a message to another object
S The message/method name is placed above the arrowed line
.
S Dotted line is return message and its optional
Figure 2
Figure 2: An example of messages being sent between objects
Figure 2
S 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.
S The system object then calls the getSecurityClearance method with
the argument of userId on the secSystem object
S The secSystem object returns userClearance to the system object
when the getSecurityClearance method is called
S The system object returns availableReports when the
getAvailableReports method is called.
Guard
S Guards are used throughout UML diagrams to control flow
S We placed the guard element above the message line being
guarded and in front of the message name.
Guard
SLoops and Conditional
Loops And Conditional
S Sequence diagrams also can show the looping and conditional
behavior.
S Treat sequence diagrams as a visualization of how objects
interact rather than as a way of modeling control logic.
S Both loops and conditionals use interaction frames ,which are
ways of marking off a piece of a sequence diagram.
S Frames consist of some region of a sequence diagrams that is
divided into one or more fragments.
S Each frame has an operators
S Each fragment may have a guard
Loops And Conditional
S To show a loop, we use the loop operator with a single fragment and put the
basis of the interaction in the guard
S 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 )
S opt : The option combination fragment is used to model a sequence that,
S
S
S
S
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 5 : Opt (“if-then”)
Figure 6 : Alt (“if-else-then”)
Figure 7 : Par
Figure 8 :Loop
Figure 8
S 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 .
S 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.
S 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
S How to create Create Sequence Diagram in Eclipse ?
Sequence Diagram
SSynchronous and
Asynchronous call
Synchronous call
S 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
Asynchronous call
S
If a caller sends an asynchronous
message, it can continue processing
and doesn’t have to wait for
response.
S
Asynchronous calls can be found in
multithreaded applications and in
message oriented middleware.
S
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
S UML sequence diagram represent behavior in terms of
interactions.
S They complement class diagrams, which represent structure.
S Useful for finding participating objects.
Comparison with other
Diagrams
S Sequence diagram
S State diagram
S Activity diagram
S Communication diagram
S Timing diagram
S …
Sequence diagram
S
Use sequence diagrams
when we want to look
at the behavior of
several objects within a
single use case.
State diagram
S
Use state diagrams when we
want to look at the behavior of a
single object across many use
cases.
Activity diagram
S
Use activity diagrams when we want to look at the behavior across
many use cases or many threads.
Sequence Diagram Application
Sequence diagrams are typically used to model
S Usage scenario
S The logic of method
S The logic of Services
Sequence Diagram
Application(I)
S Usage Scenarios. A usage scenario is a description of a
potential way your system is used.
S 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(I)
Card Holder
Sequence Diagram Applications
S
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
enrollStudent(aStudent)
isStudentEligible(aStudent)
getSeminarHistory()
seminarHistory
Eligibility Status
enrollmentStatus
Sequence Diagram Application
S
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
student
Persistance framework
Search(student,name,address,phone)
Build SQL Select
Exsist(name,address,phone)
Select statement
List of all potential matches
(vector of student object)
Result set
Student data structure
DB
The Logic of Method
enrollStudent(aStudent)
isStudentEligible(aStudent)
getSeminarHistory()
seminarHistory
Eligibility Status
enrollmentStatus
Sequence Diagram
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 seminar
7.
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.
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.
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.
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.
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.
Sequence Diagram
SSystem Sequence Diagram
(SSD)
System Sequence Diagram
(SSD) - Example
S Example
S Online Shopping
S Shopping in the store
System Sequence Diagram
(SSD) - Actor
S Actor
Specifies a role played by a user or any other system that
interacts with the system
S Generates events to a system, requesting some operation in
response
S Actors may represent roles played by human users, external
hardware, or other subjects
S UML 2 does not permit associations between Actors
S
System Sequence Diagram
(SSD) – System Events
S System Event
Item#456464646
Qty.1
S External event
S Generated by an actor
S Directly stimulates the system
S To identify system events, it is necessary to be clear on the
choice of system boundry
S Example: customer chooses an
item for purchase (ProductID, amount)
System Sequence Diagram
(SSD) – System Operation
S System operation
S Operation of the system
S
Executes in response to a
system event
S Example: System generates an
invoice (inv#,description,total amount)
Inv#6354254765
System Sequence Diagram
(SSD) – Use Case
S Use Case
S Description of a system’s behavior as it responds to a request that
originates from outside of that system
S “Who" can do "what" with the system
S Suggests how actors interact with the system
S Use cases treat the system as a black box
S Should be constructed by business domain knowledgeable people
S A use case may show one or more (more commonly more…) use
case scenarios
System Sequence Diagram
(SSD) – Use Case Cont.
S Uses cases may be written in three formality types
S Brief
S One-paragraph summary
S Usually of the main success scenario
S Casual
S Informal paragraph format
S Alternate senarios
S Fully dressed
S All steps and variations are written in detail.
System Sequence Diagram
(SSD) – Use Case Example
Brief
S Brief
S 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
S Informal Paragraph Format
S
Main success scenario:
S A customer arrives at a checkout with items to return. The
cashier uses thePOS system to record each returned item…
S
Alternate scenarios:
S 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
S 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.
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)
S What is it?
S Sequence diagram
S Created for a particular senario of a use case
S One diagram  one senarion
S Illustrates
S Events from actors to the system
S External response of the system
S Should specify and show the following:
S External actors
S Messages (methods) invoked by these actors  system events
S Return values associated with previous messages created by the system 
system operations
S Indication of any loops or iteration area
System Sequence Diagram
(SSD)
S Why is it created?
S 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
S
S
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”
S One part of that description is a SSD
S Other parts include “use cases” and “system contracts”
System Sequence Diagram
(SSD)
S When it is created?
S During analysis phase of the development process
S It is desirable to isolate and illustrare the operations that an actor
requests of a system. Why?
S
Because they are the important part of analyzing system behavior
S It depends on
S The creation of the use cases
System Sequence Diagram
(SSD)
S Which senarions should have a SSD?
S Main success senario
S Frequent senario
S Complex senario
System Sequence Diagram
(SSD)
S SSD if often accompanied by a textual description of the
senario to the left of the diagram
System Sequence Diagram
(SSD) - Naming
S How to name system events and operations
S System events should be expressed at the
level of intention
S To improve clarity, start the name of a system event with a verb
S
enterItem(itemID) instead of scan(itemID)
S Captures the intention
S Respects design choices regarding the input device used to capture
system event
S Keep the system response at an
abstract level
S
“Description, total” instead of “descrition and total”
Inter-System SSD
S SSDs can also be used to Illustrates collaboration between
systems
S Example: adding support for third-party external systems
S SSDs should be updated to reflect at least some of the inter-
system collaborations
S Tax calculator
S Credit authorization
System Sequence Diagram
(SSD) - Glossary
S What information to be placed in glossory?
S SSD elements are terse
S Details and proper explanation
S Example
S
“Change due, receipt”
S
Glossary:
S Sample receipt
S Detailed content
System Sequence Diagram
(SSD) - Summary
S 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.
Conclusion
S Sequence Diagram Advantages
S Clearly show
S
S
S
The sequence of events
When objects are created and destroyed
Concurrent operations
S Sequence Diagram Disadvantages
S
S
Take up a lot of space
Do not present the inter relationships between the collaborating objects
very well
S Do not create SSDs for all senarios
Pattern - Visitor
Amee Joshi
Monali Bhavsar
S
Outline
S
Problem
S
Motivation
S
Applications
S
Participants
S
Collaborations
S
Consequences
S
Implementation
S
Comparison with other patterns
S
Drawback
Introduction
Creational Patterns
Structural Patterns
Behavioral Patterns
Singleton
Composite
Chain of Responsibility
Abstract Factory
Façade
Command
Factory Method
Proxy
Prototype
Flyweight
• Adapter
• Bridge
• Decorator
Builder
Interpreter Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
Visitor Pattern - Intent
S Represent an operation to be performed on the elements of
an object structure.
S 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?
S 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
S The classes defining the object structure rarely change but
you often want to define new operations over the structure.
Motivation
S 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.
S One option: place all of these operations in the nodes of the
AST.
Motivation
S Operations that one would like to perform on the AST
include:
S Checking that all variables are defined
S Checking for variables being assigned before they are
used
S Type checking
S Code generation
S Pretty printing/formatting
Node class hierarchy
S These
operations may
need to treat each type of
node differently
S One way to do this is to
define each operation in
the specific node class
Problem with Node class
hierarchy
S Distributing operations across Node classes leads to a
system that’s hard to understand, maintain and change.
S It’s confusing to have type-checking code in the same class
with code to perform pretty printing.
S Also, adding a new operation, e.g. data flow analysis,
requires recompiling all of the classes
Visitor
S Allows us to separate Node classes from operations “on”
Node classes
S Allows each new operation to be added separately, without
changing Node class!
Nodes “accept” visitors
Visitor for Nodes
Applicability of Visitor Pattern
S Use the Visitor pattern when
S 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.
S 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.
S The classes defining the object structure rarely change,
but you often want to define new operations over the
structure.
Visitor Pattern- Participants
S Context(Visitor):
S Declares a Visit operation for each class of ConcreteElement
in the object structure.
S 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.
S
ConcreteVisitor
S 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- Participants
S ConcreteVisitor provides the context for the algorithm
and stores its local state.
S This state often accumulates results during the traversal
of the structure.
S Element
S Defines an Accept operation that takes a visitor as an
argument.
S ConcreteElement and/or ConcreteComposite
S Implements an Accept operation that takes a visitor as an
argument.
Visitor Pattern- Participants
S ObjectStructure
S Can enumerate its elements.
S May provide a high-level interface to allow the visitor
to visit its elements.
S May either be a composite or a collection such as a list
or a set.
Structure of Visitor Pattern
Example
S 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
S 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.
S Create a Visitor base class with a visit(ElementXxx) method
for each Element derived type.
S 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- continue
S 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.
S Create a Visitor derived class for each “operation” to be
performed on Element objects. visit() implementations will
rely on the Element’s public interface.
S The client creates Visitor objects and passes each to Element
objects by calling accept().
Collaborations
S A clients that uses the visitor pattern must create a
ConcreteVisitor object and then traverse the object structure
visiting each element with the visitor.
S 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.
Collaborations
Consequences
S Benefits:
Makes adding new operations is easy
S 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.
S Gathers related operations and separates unrelated ones
S Related behavior is localized in the visitor and not spread over
the classes defining the object structure.
S Unrelated sets of behavior are partitioned in their own visitor
subclasses.
S
Consequences
S Benefits:
S Accumulating States:
S Visitor can accumulate state rather than pass it a parameters
S 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.
S Allows visiting across class hierarchies:
S 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.
Consequences
S Liabilities
S
Adding new ConcreteElement classes is hard:
S
Must add a new method to each ConcreteVisitor subclass
S
Each new ConcreteElement gives rise to a new abstract operation on
Visitor and a corresponding implementation in every
ConcreteVisitor class.
S Breaking encapsulation:
S
Visitor’s approach assumes that the ConcreteElement interface is
powerful enough to allow the visitors to do their job.
S
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
S Double Dispatch
S The key to visitor is a double dispatch.
S The meaning of the accept operation depends on
the visitor & on the element languages that
support double dispatch(CLOS) can do without
this pattern.
S The Visitor pattern allows you to add operations to
classes without changing them using a technique
called double-dispatch
Single-Dispatch
S The actual method invoked depends on the name of
the request (method signature) and the type of the
receiver object
S For example, calling foo() on a object of Type X,
invokes the foo() methodof X
S The actual underlying type will be discovered through
polymorphism
S This is the standard technique used in languages like
Java and C++
Double-Dispatch
S
The actual method invoked depends on the name of the request and the
types of two receivers
S
For example, consider an object of type Visitor1 calling accept(Visitor1)
on an object of Type ElementA:
S The Visitor1 object dispatches a call to the accept(Visitor) method of
ElementA.
S 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.
S This round trip effectively picks up the right type of Element, ensuring
that the correct visit() method of the Visitor object is called.
S
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?
S Responsibility of traversal can be with:
S The Object Structure
S
define operation that performs traversal while applying visitor
object to each component
S The Visitor
S Must replicate traversal code in each concrete visitor.
S Visitor is advisable when a particular complex traversal is needed.
S 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
S A separate Iterator object.
S Iterator sends message to visitor with current element as argument
Example - Customers
Application.
S 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- continue
In the example we can see the following actors:
S IVisitor and IVisitable interfaces
S 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.
S GeneralReport is a visitor class and implements the IVisitor
interface.
Visitor Pattern Known Uses
S Smalltalk-80 Compiler
S IRIS Inventor Toolkit
S X Consortium’s Fresco ApplicationToolkit
S Bistro Programming Language Compiler
Visitors and Iterators
The iterator pattern and Visitor pattern has the same benefit.
used to traverse object structures.
Visitors
S
S
The visitor pattern can be used
on complex structure such as
hierarchical structures or
composite structures.
S 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
S
Iterator is intended to be used on
collections. Usually collections
contain objects of the same type.
S
The iterator is used by the client
to iterate through the objects
form a collection and the
operations are defined by the
client itself.
Visitors and Composites
S The visitor pattern can be used in addition with the
composite pattern.
S The object structure can be a composite structure.
S 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.
S Interpreter- distribute code over class hierarchy
S Visitor- centralize code in single class.
Drawback
S If a new visitable object is added to the framework structure
all the implemented visitors need to be modified.
S The separation of visitors and visitable is only in one sense:
visitors depend of visitable objects while visitable are not
dependent of visitors.
S Part of the dependency problems can be solved by using
Reflection with a performance cost.
Visitor Pattern using Reflection
S Reflection can be used to overcome the main drawback of
the visitor pattern.
S When the standard implementation of visitor pattern is
used the method to invoke is determined at runtime.
S Reflection is the mechanism used to determine the method
to be called at compile-time.
S 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
S 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.
Example - continue
Java Source code
Continue
Continue
Refrences
S
Applying UML and Patterns, Larman c., second edition
S
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
S
http://www.ibm.com/developerworks/rational/library/3101.html
S
www.Wikipedia.com
S
http://www.tracemodeler.com/articles/
a_quick_introduction_to_uml_sequence_diagrams/
S
http://www.zicomi.com/combinedFragmentCriticalRegion.jsp
S
http://en.wikipedia.org/wiki/Visitor_pattern
S
http://sourcemaking.com/design_patterns/visitor
S
http://www.csee.umkc.edu/~leeyu/class/CS590L-04/Presentation/Visitor.pdf
S Thank you
Download