【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();
    }
}

运行结果

相关推荐
xiaowu08022 分钟前
C# 嵌入资源加载 + 外部配置文件的兜底配置
开发语言·c#
马达加斯加D43 分钟前
Web系统设计 --- 接口防抖
c#
wen__xvn1 小时前
C++ 中 std::set 的用法
java·c++·c#
kylezhao20192 小时前
C#读取字节数组某个位的值
开发语言·c#
我是唐青枫4 小时前
深入理解 Interlocked.CompareExchange:C#.NET 原子操作核心原理
c#·.net
拾荒的小海螺5 小时前
C#:PdfiumViewer 高效解析和操作 PDF 的技术指南
开发语言·pdf·c#
缺点内向5 小时前
C#: 精准掌控Excel工作流——激活工作表与选择单元格实战
开发语言·c#·excel
一刻钟.6 小时前
DataGridView和定时器
开发语言·c#
咕白m6256 小时前
通过 C# 拆分 Excel 工作表
后端·c#
小股虫6 小时前
数据库外科手术:一份拖垮系统的报表,如何倒逼架构演进
数据库·微服务·设计模式·架构·方法论