From b4f9bc89479682dcb3e5c9fcdc3c9d5b24fb68ae Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 25 Oct 2022 01:06:36 +0100 Subject: [PATCH] pattern --- Behavioral/Visitor/csharp/Program.cs | 70 ++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Behavioral/Visitor/csharp/Program.cs diff --git a/Behavioral/Visitor/csharp/Program.cs b/Behavioral/Visitor/csharp/Program.cs new file mode 100644 index 0000000..ea85a0e --- /dev/null +++ b/Behavioral/Visitor/csharp/Program.cs @@ -0,0 +1,70 @@ +using System.Text; + +namespace DesignPatters +{ + using DictType = Dictionary>; + + public abstract class Expression + { + + } + + public class DoubleExpression : Expression + { + public double Value { get; set; } + + public DoubleExpression(double value) + { + this.Value = value; + } + } + + public class AdditionExpression : Expression + { + public Expression Left; + public Expression Right; + + public AdditionExpression(Expression left, Expression right) + { + Left = left ?? throw new ArgumentNullException(paramName: nameof(left)); + Right = right ?? throw new ArgumentNullException(paramName: nameof(right)); + } + } + + public static class ExpressionPrinter + { + private static DictType actions = new DictType + { + [typeof(AdditionExpression)] = (e, sb) => + { + var ae = (AdditionExpression)e; + sb.Append("("); + Print(ae.Left, sb); + sb.Append("+"); + Print(ae.Right, sb); + sb.Append(')'); + }, + [typeof(DoubleExpression)] = (e, sb) => + { + var de = (DoubleExpression)e; + sb.Append(de.Value); + } + }; + public static void Print(Expression e, StringBuilder sb) + { + actions[e.GetType()](e, sb); + } + } + + public class Demo + { + public static void Main() + { + var e = new AdditionExpression(new DoubleExpression(2), new AdditionExpression(new DoubleExpression(2),new DoubleExpression(2))); + var sb = new StringBuilder(); + ExpressionPrinter.Print(e, sb); + Console.WriteLine(sb.ToString()); + + } + } +} \ No newline at end of file