CSharp - Design Patterns Visitor Pattern

Introduction

Visitor Pattern performed on the elements of an object structure.

Visitor Pattern can define a new operation without changing the classes of the elements on which it operates.

In Visitor Pattern, we can separate an algorithm from the object structure on which it operates.

Demo

using System;

interface IOriginalInterface
{
    void accept(IVisitor visitor);
}
class MyClass : IOriginalInterface
{
    private int myInt = 5;//Initial or default value

    public int MyInt
    {//  www.  j  a  v  a2  s  . c  om
        get
        {
            return myInt;
        }
        set
        {
            myInt = value;
        }
    }
    public void accept(IVisitor visitor)
    {
        Console.WriteLine("Initial value of the integer:{0}", myInt);
        visitor.visit(this);
        Console.WriteLine("\nValue of the integer now:{0}", myInt);
    }
}

interface IVisitor
{
    void visit(MyClass myClassElement);
}
class Visitor : IVisitor
{
    public void visit(MyClass myClassElement)
    {
        Console.WriteLine("Visitor is trying to change the integer value");
        myClassElement.MyInt = 100;
        Console.WriteLine("Exiting from Visitor- visit");
    }
}
class Program
{
    static void Main(string[] args)
    {
        IVisitor v = new Visitor();
        MyClass myClass = new MyClass();
        myClass.accept(v);
        Console.ReadLine();
    }
}

Result