Visitor Pattern Code Review

Define the Pattern Interface and Handler Objects

Code Download

  • Download Description:visitor pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:11 KB

Code Review

Code Walkthrough

Define the IVisitor interface to be used as the "blueprint" for the main application classes.

interface IVisitor { void Visit(Element element); }

This interface defines the Visit() method, which accepts the object to be visited as a parameter.

The PrintVisitor class (object) invokes the Accept() method on the class (object) to be visited.

class PrintVisitor : IVisitor { public void Print(Element element) { element.Accept(this);
if (element.Child != null) { Console.Write(" ["); Print(element.Child); } if (element.Next != null) { Print(element.Next); Console.Write("] "); } } public void Visit(Element element) { Console.Write(" {0}", element.Weight); } }

The visited class, in turn, invokes the Visit() method on the PrintVisitor class. The Visit() method contains the process (code) that needs to be executed against the visited class (object) each time the object is visited.

The StructureVisitor class (object) invokes the Accept() method on the class (object) to be visited.

class StructureVisitor : IVisitor { public Int32 Lab { get; set; } public Int32 Test { get; set; }
public void VisitAllLabTest(Element element) { element.Accept(this);
if (element.Child != null) { this.VisitAllLabTest(element.Child.Next); } if (element.Next != null) { this.VisitAllLabTest(element.Next); } } public void Visit(Element element) { if(((element is MidTerm) || (element is Exam)) && (element.Child==null)) { this.Test += element.Weight; return; } if (element is Lab) { this.Lab += element.Weight; return; } if (element is Test) { this.Test += element.Weight; return; } } }

The visited class, in turn, invokes the Visit() method on the StructureVisitor class. The Visit() method contains the process (code) that needs to be executed against the visited class (object) each time the object is visited.