Visitor Pattern

 Rate It (1)

The visitor design pattern enables us to create new operations to be
performed on an existing structure. The new operations don’t change the
classes/nodes. With the pattern you define two class hierarchies.
The first for the elements which the operations will operate on.
The second is for the visitors that define the operations on the elements.
The pattern is rarely used but it is common in compilers implementation.
 
Use Cases for the Visitor Pattern

You should use the pattern in the following cases:

  • You have a class hierarchy with many distinct operations.
  • The classes that defined in the object structure rarely change, but you
    need sometimes to define new operations on the object structure.

UML Diagram    
Visitor Pattern     

Example in C#
The following code is an example of how to implement the pattern:

    #region Visitor

    public interface IVisitor

    {

        #region Methods

        void Visit(Element element);

        #endregion

    }

    #endregion

    #region Visitor Concrete

    public class VisitorConcreteA : IVisitor

    {

        #region IVisitor Members

        public void Visit(Element element)

        {

            Console.WriteLine("{0} Visited {1}",

                this.GetType().Name, element.GetType().Name); 

        }

        #endregion

    }

    public class VisitorConcreteB : IVisitor

    {

        #region IVisitor Members

        public void Visit(Element element)

        {

            Console.WriteLine("{0} Visited {1}",

                this.GetType().Name, element.GetType().Name); 

        }

        #endregion

    }

    #endregion

    #region Element

    public interface IElement

    {

        #region Methods

        void Accept(IVisitor visitor);

        #endregion

    }

    public abstract class Element : IElement

    {

        #region IElement Members

        public void Accept(IVisitor visitor)

        {

            visitor.Visit(this);

        }

        #endregion

    }

    #endregion

    #region Concrete Element

    public class ElementConcreteA : Element

    {

        // implement whatever you need

    }

    public class ElementConcreteB : Element

    {

        // implement whatever you need

    }

    #endregion

    #region Object Structure

    public class ObjectStructure

    {

        #region Members

        private List<Element> _elements;

        #endregion

        #region Ctor

        /// <summary>

        /// Construct a new object structure

        /// </summary>

        public ObjectStructure()

        {

            _elements = new List<Element>();

        }

        #endregion

        #region Methods

        /// <summary>

        /// Attach the given element to the object structure

        /// </summary>

        /// <param name="element">The element to attach</param>

        public void AttachElement(Element element)

        {

            _elements.Add(element);

        }

        /// <summary>

        /// Detaches the given element from the object structure

        /// </summary>

        /// <param name="element">The element to detach</param>

        public void DetachElement(Element element)

        {

            _elements.Remove(element);

        }

        /// <summary>

        /// Perform accept operation on all the object structure

        /// with the given visitor

        /// </summary>

        /// <param name="visitor">The given visitor</param>

        public void Accept(IVisitor visitor)

        {

            foreach (Element element in _elements)

            {

                element.Accept(visitor);

            }

        }

        #endregion

    }

    #endregion

In the example I use an object structure that is implemented with
an inner list. You can use whatever object structure you need in order to
implement the pattern. As can be seen in the example, I use two main
interfaces to implement the pattern – IVisitor and IElement. The IElement
dictates the Accept method to the Element abstract class which every concrete
element implement (I could drop the IElement or the Element class but I have chosen
not to). Every visitor concrete implement the Visit operation to perform the
desired operation (in my implementation the Visit method is implement the same in
both concrete classes).

The next code shows an example of how to use the classes above:

   // Build the structure

   ObjectStructure structure = new ObjectStructure();

   structure.AttachElement(new ElementConcreteA());

   structure.AttachElement(new ElementConcreteB());

   // Create visitor objects

   VisitorConcreteA visitorA = new VisitorConcreteA();

   VisitorConcreteB visitorB = new VisitorConcreteB();

   // Structure accepting visitors

   structure.Accept(visitorA);

   structure.Accept(visitorB);

   Console.Read();

Summary
To sum up, you were introduced to the visitor design pattern.
The pattern is used in order to extend elements of an object structure with new
operations without the need to change the elements.
As written earlier the pattern is rarely used.

Revision number 1, Thursday, October 02, 2008 9:03:58 PM by gilfink

Comments

Related Articles

Design Patterns

Design Patterns Design patterns are recognized solutions to common problems defined originally by the Gang of Four programmers. Design patterns are used throughout the ASP.NET Framework. The various patterns are commonly divided into several different groups

Prototype Pattern

The prototype is built upon the use of object cloning. The prototype creates new objects by cloning one of its concrete classes. The prototype is used in the following situations: You need to hide the concrete product classes from the client. You want to reduce

Threat Modeling

It's absolutely necessary if you're serious about security. Whitepapers/Books/Blogs Threat Modeling for ASP.NET (PDF) - an excellent white paper from Rüdiger Grimm and Henrik Eichstädt from the University of Kent Threat Modeling book from MSPress

IDisposable Pattern

The IDisposable pattern isn't one of the a classic patterns. It's a pattern suggested in MSDN to implement the IDisposable interface. You should be familiar with the pattern or with the interface because it's a basic thing to know about the .Net

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (7)
  2. yrb.yogi (5)
  3. srinivaskotra (3)
  4. XIII (2)
  5. rdmartin33 (2)
  6. Babunareshnarra (2)
  7. Dungimon (1)
  8. ali62b (1)
Microsoft Communities