June 12, 2007

Design Patterns - Visitor Pattern

The Visitor Pattern is a solution for a problem where you have many Objects, each Object is similar but you wish to extract information (such as a print statement) on each Object in a different way.
E.g. You have a collection of Objects, each of your objects has different member variables and you want some way to call print this info. One way to do it would be to cycle through each object and Call some common method on each such as Print(), this ties the Object tightly to the printing or whatever you are doing, we want to loosly couple the printing or whatever to the object itself, to unbind the Printing from the actual Object we introduce 2 interfaces. The Visitor and the Visitable.
The Visitor interface has a Visit(object) method (this is what would print the details).
The Visitable interface has an Accept method, this takes the Visiting object as a parameter.
The Object we want to print implements the Visitable interface, this has a callback to the implementor of the Visitor Interface, this callback is required because it is actually the implementor of the Visitor that does the printing.
The implementor of the Visitor has a visit(Object) method for each Object type, this removes the need for Use/Case statements for each Object type.

using System;
using System.Collections.Generic;
using System.Text;

namespace VisitorPattern
{
interface Visitor
{
void visit(Car car);
void visit(Bus bus);
}

interface Visitable
{
void accept(Visitor visitor);
}

class Car : Visitable
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}

class Bus : Visitable
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}

class PrintVisitor : Visitor
{
public void visit(Car car)
{
Console.WriteLine("Visiting car");
}
public void visit(Bus bus)
{
Console.WriteLine("Visiting bus");
}
}

public class VisitorDemo
{
static public void main(String[] args)
{
Visitable[] objects = { new Car(), new Bus() };
Visitor visitor = new PrintVisitor();
foreach (Visitable visited in objects)
{
visited.accept(visitor);
}
}
}
}