Visitor Pattern can be replaced with Callback functions?

Posted by getit on Stack Overflow See other posts from Stack Overflow or by getit
Published on 2012-12-07T22:40:19Z Indexed on 2012/12/07 23:04 UTC
Read the original article Hit count: 238

Is there any significant benefit to using either technique? In case there are variations, the Visitor Pattern I mean is this: http://en.wikipedia.org/wiki/Visitor_pattern

And below is an example of using a delegate to achieve the same effect (at least I think it is the same)

Say there is a collection of nested elements: Schools contain Departments which contain Students

Instead of using the Visitor pattern to perform something on each collection item, why not use a simple callback (Action delegate in C#)

Say something like this

class Department
{
    List Students;
}

class School
{
    List Departments;

    VisitStudents(Action<Student> actionDelegate)
    {
        foreach(var dep in this.Departments)
        {
            foreach(var stu in dep.Students)
            {
                actionDelegate(stu);
            }
        }
    }
}

School A = new School();
...//populate collections

A.Visit((student)=> { ...Do Something with student... });

*EDIT Example with delegate accepting multiple params

Say I wanted to pass both the student and department, I could modify the Action definition like so: Action

class School
{
    List Departments;

    VisitStudents(Action<Student, Department> actionDelegate, Action<Department> d2)
    {
        foreach(var dep in this.Departments)
        {
            d2(dep); //This performs a different process.
            //Using Visitor pattern would avoid having to keep adding new delegates.
            //This looks like the main benefit so far 
            foreach(var stu in dep.Students)
            {
                actionDelegate(stu, dep);
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about design-patterns