Difference between revisions of "Visitor"

From CDOT Wiki
Jump to: navigation, search
(UML Diagram)
Line 14: Line 14:
  
 
The key is the Accept method in the ConcreteElement classes. The body of this method shows the double dispatching call, where the Visitor is passed in to the accept method, and that visitor is told to execute its visit method, and is handed the node by the node itself. This makes for very robust code, since all of the decision making as to what to execute where and when it taken care of by the dispatching.
 
The key is the Accept method in the ConcreteElement classes. The body of this method shows the double dispatching call, where the Visitor is passed in to the accept method, and that visitor is told to execute its visit method, and is handed the node by the node itself. This makes for very robust code, since all of the decision making as to what to execute where and when it taken care of by the dispatching.
 +
 +
 +
== Code Examples ==

Revision as of 21:15, 8 April 2007

Visitor Pattern (Object Behavioral)

Represents an operation to be performed on the elements of an object Structure. Visitor lets you define a new operation withou changing the classes of the elements on which it operates.

Prupose

The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure. In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.

Each node in the data structure "accepts" a Visitor, which sends a message to the Visitor which includes the node's class. The visitor will then execute its algorithm for that element. This process is known as "Double Dispatching." The node makes a call to the Visitor, passing itself in, and the Visitor executes its algorithm on the node. In Double Dispatching, the call made depends upon the type of the Visitor and of the Host (data structure node), not just of one component.

UML Diagram

Visitor.jpg

The key is the Accept method in the ConcreteElement classes. The body of this method shows the double dispatching call, where the Visitor is passed in to the accept method, and that visitor is told to execute its visit method, and is handed the node by the node itself. This makes for very robust code, since all of the decision making as to what to execute where and when it taken care of by the dispatching.


Code Examples