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
- Visitor Pattern Code Review: Define the Pattern Interface and Handler Objects
- Visitor Pattern Code Review: Define the Element Interface and Handler Objects
- Visitor Pattern Code Review: Define the Context Object
- Visitor Pattern Code Review: Use the Visitor Pattern
Code Walkthrough
Define the IVisitor interface to be used as the "blueprint" for the main application classes.
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.
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.
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.
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!