Monday, September 26, 2011

Visitor Design Pattern

In Simple words - In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to easily follow the open/closed principle.


UML:
File:VisitorClassDiagram.svg


The participants classes in this pattern are:
  • Visitor - This is an interface or an abstract class used to declare the visit operations for all the types of visitable classes. Usually the name of the operation is the same and the operations are differentiated by the method signature: The input object type decides which of the method is called.

  • ConcreteVisitor - For each type of visitor all the visit methods, declared in abstract visitor, must be implemented. Each Visitor will be responsible for different operations. When a new visitor is defined it has to be passed to the object structure.

  • Element- is an abstraction which declares the accept operation. This is the entry point which enables an object to be "visited" by the visitor object. Each object from a collection should implement this abstraction in order to be able to be visited.

  • ConcreteElement - Those classes implements the Visitable interface or class and defines the accept operation. The visitor object is passed to this object using the accept operation.


A user object receives a pointer to another object which implements an algorithm. 


A Diagram of the Java Code Example.        I, the copyright holder of this work, hereby release it into the public domain.  This applies worldwide. In case this is not legally possible, I grant any entity the right to use this work for any purpose, without any conditions, unless such conditions are required by law.


The visitor pattern is used when:


  • Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).

  • There are many distinct and unrelated operations needed to be performed. Visitor pattern allows us to create a separate visitor concrete class for each type of operation and to separate this operation implementation from the objects structure.

  • The object structure is not likely to be changed but is very probable to have new operations which have to be added. Since the pattern separates the visitor (representing operations, algorithms, behaviors) from the object structure it's very easy to add new visitors as long as the structure remains unchanged.








No comments:

Post a Comment