All Topics  
Visitor pattern

 

   Email Print
   Bookmark   Link






 

Visitor pattern



 
 
In object-oriented programming
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
 and software engineering
Software engineering

Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches....
, the visitor design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
 is a way of separating an algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 from an object structure upon which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. Thus, using the visitor pattern helps conformance with the open/closed principle
Open/closed principle

In object-oriented programming, the open/closed principle states "software entities should be open for extension, but closed for modification";...
.

In essence, the visitor allows one to add new virtual function
Virtual function

In object-oriented programming, a virtual function or virtual method is one whose behavior can be Method overriding within an inheriting class by a function with the same Method signature....
s to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function.






Discussion
Ask a question about 'Visitor pattern'
Start a new discussion about 'Visitor pattern'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In object-oriented programming
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
 and software engineering
Software engineering

Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches....
, the visitor design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
 is a way of separating an algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 from an object structure upon which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. Thus, using the visitor pattern helps conformance with the open/closed principle
Open/closed principle

In object-oriented programming, the open/closed principle states "software entities should be open for extension, but closed for modification";...
.

In essence, the visitor allows one to add new virtual function
Virtual function

In object-oriented programming, a virtual function or virtual method is one whose behavior can be Method overriding within an inheriting class by a function with the same Method signature....
s to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch
Double dispatch

In software engineering, double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call....
.

While powerful, the visitor pattern is more limited than conventional virtual functions. It is not possible to create visitors for objects without adding a small callback method inside each class and the callback method in each of the classes is not inheritable.

Elaborated

The idea is to use a structure of element classes, each of which has an accept method that takes a visitor object as an argument. Visitor is an interface
Interface (computer science)

Interface generally refers to an Abstraction_%28computer_science%29 that an entity provides of itself to the outside. This separates the methods of external communication from internal operation, and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide Polymorphism in object-orien...
 that has a visit method for each element class. The accept method of an element class calls back the visit method for its class. Separate concrete visitor classes can then be written that perform some particular operations, by implementing these operations in their respective visit methods.

One of these visit methods of a concrete visitor can be thought of as a method not of a single class, but rather a method of a pair of classes: the concrete visitor and the particular element class. Thus the visitor pattern simulates double dispatch
Double dispatch

In software engineering, double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call....
 in a conventional single-dispatch object-oriented language such as Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
, Smalltalk
Smalltalk

Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al...
, and C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
. For an explanation of how double dispatch differs from function overloading, see Double dispatch is more than function overloading
Double dispatch

In software engineering, double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call....
 in the double dispatch article. In the Java language, two techniques have been documented which use reflection to simplify the mechanics of double dispatch simulation in the visitor pattern: (the Walkabout variation), and .

The visitor pattern also specifies how iteration occurs over the object structure. In the simplest version, where each algorithm needs to iterate in the same way, the accept method of a container element, in addition to calling back the visit method of the visitor, also passes the visitor object to the accept method of all its constituent child elements.

Because the Visitor object has one principal function (manifested in a plurality of specialized methods) and that function is called visit, the Visitor can be readily identified as a potential function object
Function object

A function object, also called a functor, functional or functionoid, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function , usually with the same syntax....
 or functor
Functor

In category theory, a branch of mathematics, a functor is a special type of mapping between categories. Functors can be thought of as morphisms in the category of small categories....
. Likewise, the accept function can be identified as a function applicator, a mapper, which knows how to traverse a particular type of object and apply a function to its elements. Lisp's object system with its multiple dispatch does not replace the Visitor pattern, but merely provides a more concise implementation of it in which the pattern all but disappears.

Example in Java

The following example is in the Java programming language: interface CarElementVisitor interface CarElement class Wheel implements CarElement

class Engine implements CarElement

class Body implements CarElement

class Car

class CarElementPrintVisitor implements CarElementVisitor

class CarElementDoVisitor implements CarElementVisitor

public class VisitorDemo


Example in D

The following example is in the D programming language: import std.stdio; import std.string;

interface CarElementVisitor

interface CarElement

class Wheel : CarElement

class Engine : CarElement

class Body : CarElement

class Car

class CarElementPrintVisitor : CarElementVisitor

class CarElementDoVisitor : CarElementVisitor

void main



Example in C++

The following example is an example in the C++ programming language:
  1. include
  2. include
  3. include


using namespace std;

class Wheel; class Engine; class Body; class Car;

// interface to all car 'parts' struct CarElementVisitor ;

// interface to one part struct CarElement ;

// wheel element, there are four wheels with unique names class Wheel : public CarElement ;

// engine class Engine : public CarElement ;

// body class Body : public CarElement ;

// car, all car elements(parts) together class Car ;

// PrintVisitor and DoVisitor show by using a different implementation the Car class is unchanged // even though the algorithm is different in PrintVisitor and DoVisitor. class CarElementPrintVisitor : public CarElementVisitor ;

class CarElementDoVisitor : public CarElementVisitor ;

int main



State

Aside from potentially improving separation of concerns
Separation of concerns

In computer science, separation of concerns is the process of breaking a computer program into distinct features that overlap in functionality as little as possible....
, the visitor pattern has an additional advantage over simply calling a polymorphic method: a visitor object can have state. This is extremely useful in many cases where the action performed on the object depends on previous such actions.

An example of this is a pretty-printer in a programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
 implementation (such as a compiler
Compiler

A compiler is a computer program that transforms source code written in a programming language into another computer language . The most common reason for wanting to transform source code is to create an executable program....
 or interpreter). Such a pretty-printer object (implemented as a visitor, in this example), will visit nodes in a data structure, that represents a parsed and processed program. The pretty-printer will then generate a textual representation of the program tree. In order to make the representation human readable, the pretty-printer should properly indent program statements and expressions. The current indentation level can then be tracked by the visitor as its state, correctly applying encapsulation, whereas in a simple polymorphic method invocation, the indentation level would have to be exposed as a parameter and the caller would rely on the method implementation to use and propagate this parameter correctly.

See also

  • Double
    Double dispatch

    In software engineering, double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call....
     and multiple dispatch
    Multiple dispatch

    Multiple dispatch or multimethods is the feature of some object-oriented programming languages in which a function or method can be dynamically dispatched based on the run time type of more than one of its arguments....
  • Composite pattern
    Composite pattern

    In computer science, the composite pattern is a partitioning design pattern . Composite allows a group of objects to be treated in the same way as a single instance of an object....
  • Hierarchical visitor pattern
    Hierarchical visitor pattern

    In software engineering, the hierarchical visitor pattern is one of design pattern that intend to provide a way to visit every node in the hierarchical data structure such as a tree data structure....
  • Strategy pattern
    Strategy pattern

    In computer programming, the strategy pattern is a particular design pattern , whereby algorithms can be selected at runtime.In some programming languages, such as those without Polymorphism , the issues addressed by this pattern are handled through forms of Reflection , such as the native function pointer or function Delegation syntax....
  • Function object
    Function object

    A function object, also called a functor, functional or functionoid, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function , usually with the same syntax....


External links

  • by Robert C. Martin - a rough chapter from The Principles, Patterns, and Practices of Agile Software Development, Robert C. Martin, Prentice Hall
  • (a Design Description Language)
  • Article " by Bertrand Meyer
    Bertrand Meyer

    Bertrand Meyer is an academic, author, and consultant in the field of computer languages. He created the Eiffel ....
     and Karine Arnout, Computer (IEEE), vol. 39, no. 7, July 2006, pages 23-30.
  • Article "" by Paul Mukherjee
  • Article ""
  • Article
  • Article "" by Jens Palsberg and C. Barry Jay. 1997 IEEE-CS
    IEEE Computer Society

    IEEE Computer Society is an organizational unit of the Institute of Electrical and Electronics Engineers . It was established in 1963 when the American Institute of Electrical Engineers and the Institute of Radio Engineers merged to create the IEEE....
     COMPSAC
    Software engineering

    Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches....
     paper showing that accept methods are unnecessary when reflection is available; introduces term 'Walkabout' for the technique.
  • Article "" by Bruce Wallace
  • Article "" by Anand Shankar Krishnamoorthi
  • as a universal model of terminating computation.
  • using reflection(java).
  • , Provides a context-free and type-safe implementation of the Visitor Pattern in Java based on Delegates.