【C#设计模式(16)——解释器模式(Interpreter Pattern)】

前言

解释器模式是用来解释和执行特定的语法或表达式。它将一种表达式的规则和语义进行抽象和封装,然后通过解释器来解析和执行这些规则,将其转化为可执行的操作。

代码

csharp 复制代码
 //抽象表达式
 public interface Expression
 {
     int Interpret(Context context); //解释方法
 }
 //终止符表达式
 public class NumberExpression : Expression
 {
     private int number;
     public NumberExpression(int number)
     {
         this.number = number;
     }
     public int Interpret(Context context)
     {
         return number;
     }
 }
 //非终结符表达式
 public class AddExpression : Expression
 {
     private Expression Left;
     private Expression Right;

     public AddExpression(Expression left, Expression right)
     {
         this.Left = left;
         this.Right = right;
     }
     public int Interpret(Context context)
     {
         return Left.Interpret(context)+Right.Interpret(context);
     }
 }
 //非终结符表达式
 public class MultiplyExpression:Expression
 {
     private Expression Left;
     private Expression Right;
     public MultiplyExpression(Expression left, Expression right)
     {
         Left = left;
         Right = right;
     }
     public int Interpret(Context context)
     {
         return Right.Interpret(context)*Left.Interpret(context);
     }
 }
 // 上下文
 public class Context
 {
     private int variable;
    public int Variable { get { return variable; } set { variable = value; } }

 }

/*
 * 行为型模式:Behavioral Pattern
 * 解释器模式:Interpreter Pattern
 */
internal class Program
{
    static void Main(string[] args)
    {
        //解释器语法术
        Expression expression = new AddExpression(new NumberExpression(120),
            new AddExpression(
                new NumberExpression(5),
                new NumberExpression(2))
            );
        Context context = new Context();
        int result =  expression.Interpret(context);
        Console.WriteLine($"{result}");

        //
        Expression multiflyExpression = new MultiplyExpression(new NumberExpression(2),new NumberExpression(6));

        Context context2 = new Context();
        context2.Variable = 5;
        int result2 = multiflyExpression.Interpret(context2);
        Console.WriteLine($"{result2}{Environment.NewLine}{context2.Variable}");
        Console.ReadLine();
    }
}

运行结果

相关推荐
偶尔的鼠标人几秒前
SqlSugar查询字符串转成Int的问题
c#·sqlsugar
我不是程序猿儿2 分钟前
【C#】WinForms 控件句柄与 UI 刷新时机
开发语言·ui·c#
聪明努力的积极向上4 小时前
【C#】HTTP中URL编码方式解析
开发语言·http·c#
关关长语6 小时前
(四) Dotnet中MCP客户端与服务端交互通知日志信息
ai·c#·mcp
喝茶与编码6 小时前
工厂模式+抽象类 实战指南(基于文档导出业务)
设计模式
小码编匠6 小时前
WPF 动态模拟CPU 使用率曲线图
后端·c#·.net
聪明努力的积极向上7 小时前
【.NET】依赖注入浅显解释
c#·.net
hixiong1237 小时前
C# OpencvSharp使用lpd_yunet进行车牌检测
开发语言·opencv·计算机视觉·c#
专注VB编程开发20年10 小时前
.net c#音频放大,音量增益算法防止溢出
算法·c#·音频处理·录音·音量增益·增益控制
昨天的猫10 小时前
原来项目中的观察者模式是这样玩的
后端·设计模式