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

运行结果

相关推荐
強云3 小时前
23种设计模式 - 模板方法
设计模式·模板方法
软件黑马王子5 小时前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#
shepherd枸杞泡茶5 小时前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
workflower9 小时前
Prompt Engineering的重要性
大数据·人工智能·设计模式·prompt·软件工程·需求分析·ai编程
Aimeast12 小时前
关于选择最佳.NET Core SSH服务器库的全面分析
c#·ssh
蒋劲豪12 小时前
WPF项目暴露WebApi接口;WinForm项目暴露WebApi接口;C#项目暴露WebApi接口;
开发语言·c#·wpf
ox008012 小时前
C++ 设计模式-中介者模式
c++·设计模式·中介者模式
扣丁梦想家13 小时前
设计模式教程:中介者模式(Mediator Pattern)
设计模式·中介者模式
花王江不语13 小时前
设计模式学习笔记
笔记·学习·设计模式
code bean14 小时前
【C# 数据结构】队列 FIFO
开发语言·数据结构·c#