Pattern: Visitor
Visitor pattern is a way of separating an algorithm from an object structure on which it operates.
A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.
Purpose of .NET implementation
Roslyn is a syntax analyzer for C#.
You want to provide a way for other to analyze/modify the syntax of a C# code.
You can use the Visitor pattern to traverse the syntax tree and perform operations on the nodes of the tree.
The Visitor pattern allows you to separate the algorithm from the data structure, making it easier to add new operations to the syntax tree without modifying the existing classes.
Example in .NET :
Visitor
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Visitor;
internal class VisitorDemo
{
public static void VisitMethods()
{
var Code = @"""
using System;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
var dt=DateTime.Now;
Console.WriteLine(dt);
}
}
}
""";
var tree = CSharpSyntaxTree.ParseText(Code);
var node = tree.GetRoot();
MethodVisiting LG = new MethodVisiting();
//start visiting
var sn = LG.Visit(node);
}
}
public class MethodVisiting : CSharpSyntaxRewriter
{
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
if (node.Body == null || node.Body.Statements.Count == 0)
return base.VisitMethodDeclaration(node);
var parent = node.Parent as ClassDeclarationSyntax;
if (parent == null)
return base.VisitMethodDeclaration(node);
var nameMethod = node.Identifier.Text;
var nameClass = parent.Identifier.Text;
Console.WriteLine($"visiting {nameMethod} from {nameClass}");
return base.VisitMethodDeclaration(node);
}
}
See Source Code for Microsoft implementation of Visitor
SourceCode CSharpSyntaxRewriterLearn More
C2WikiC2Wiki
dofactory
DPH
Wikipedia
Homework
Implement a visitor that will allow you to calculate the total price of a shopping cart.
The shopping cart should contain items with a price and a quantity.
Visit every item and make the sum.