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

运行结果

相关推荐
bugcome_com3 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
BD_Marathon4 小时前
设计模式——合成复用原则
设计模式·合成复用原则
懒人咖13 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com13 小时前
深入了解 C# 编程环境及其开发工具
c#
书院门前细致的苹果14 小时前
设计模式大全:单例、工厂模式、策略模式、责任链模式
设计模式·责任链模式·策略模式
wfserial15 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师17 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201918 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
啦啦啦_999918 小时前
Redis-5-doFormatAsync()方法
数据库·redis·c#
Porco.w19 小时前
C#与三菱PLC FX5U通信
网络·c#