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

运行结果

相关推荐
半路下车32 分钟前
【Harmony OS 5】HarmonyOS应用测试指南
设计模式·harmonyos
周某某~39 分钟前
一.设计模式的基本概念
设计模式
~plus~1 小时前
Harmony核心:动态方法修补与.NET游戏Mod开发
开发语言·jvm·经验分享·后端·程序人生·c#
htj101 小时前
C# 使用正则表达式
正则表达式·c#
on the way 1231 小时前
行为型设计模式之Interpreter(解释器)
设计模式
cui_hao_nan1 小时前
设计模式——模板方法
java·设计模式
~plus~1 小时前
WPF八大法则:告别模态窗口卡顿
开发语言·经验分享·后端·程序人生·c#
在未来等你1 小时前
Java并发编程实战 Day 11:并发设计模式
java·设计模式·多线程·并发编程·threadlocal·生产者消费者·读写锁
就是有点傻1 小时前
使用WPF的Microsoft.Xaml.Behaviors.Wpf中通用 UI 元素事件
c#
qq_297908012 小时前
C#报价系统陈列展示成本核算系统项目管理系统纸品非纸品报价软件
sqlserver·c#·.net·开源软件