Visitor Pattern

Developers find it difficult to understand and implement the Visitor Pattern.Below is a simple example which shows how to implement and use the Visitor Pattern in C#.

 

Visitor Design pattern is a way of Injecting Operations into a concrete entity without modifying its object structure . A concrete Object is made “visitable” and Visitor “visits” the concrete object to perform operations

Class Diagram

 

Source Code

Visitor Interface

 

 interface IVisitable    {

        void Accept(IIncomeVisitor visitor);

    }

 

Visitable Interface

interface IVisitable    {

        void Accept(IIncomeVisitor visitor);

    }

A Sample Visitor

     class TaxVisitor : IIncomeVisitor

    {

        double tax;

        public void Visit(Income i)

        {

            tax = i.TotalIncome * 0.40;

        }

 

        public double ValueDeducted

        {

            get { return tax; }

        }

    }

 A  Concrete "Visitable" Class

 

    class Income : IVisitable

    {

        int m_totalIncome = 0;

 

        public int TotalIncome

        {

            get { return m_totalIncome; }

            set { m_totalIncome = value; }

        }

 

        public Income(int totalIncome)

        {

            m_totalIncome = totalIncome;

        }

 

        public void Accept(IIncomeVisitor visitor)

        {

            visitor.Visit(this);

        }

    }

 

Sample Code attached