设计模式(十五):解释器模式

一、定义

在设定环境中,定义一种规则或者语法,通过解释器来解释规则或者语法的含义.

二、实例:将  二十一    —>    21

2.1 设定我们的环境 Context

 public class Context
    {
        public string Input { get; set; }
        public int Output { get; set; }
    }

2.2 根据语法来解释

抽象解释器:

 public abstract class Interpreter
    {
        public string FlagStr { get; set; }
        public int Num { get; set; }
        public abstract int Interpret(Context context);
    }

具体解释:

二=2

复制代码
  public class Two : Interpreter
    {
        public Two()
        {
            FlagStr = "";
            Num = 2;
        }

        public override int Interpret(Context context)
        {
            return Num;
        }
    }
复制代码

一=1

复制代码
 public class One : Interpreter
    {
        public One()
        {
            FlagStr = "";
            Num = 1;
        }

        public override int Interpret(Context context)
        {
            return Num;
        }
    }
复制代码

十=*10

复制代码
 public class Tenfold : Interpreter
    {
        public Tenfold()
        {
            FlagStr = "";
            Num = 10;
        }
        public override int Interpret(Context context)
        {
            return context.Output*Num;
        }
    }
复制代码

再封装一下:

复制代码
 public class InterpretPrivoder
    {
        public int FormatStr(Context context)
        {
            foreach (char c in context.Input)
            {
                switch (c)
                {
                    case '': context.Output += new One().Interpret(context); break;
                    case '': context.Output += new Two().Interpret(context); break;
                    case '': context.Output = new Tenfold().Interpret(context); break;
                }
            }
            return context.Output;
        }
    }
复制代码

其中,未结束符为二和一,结束符为十

客户端:

 //------------------------解释器模式-----------------------
            Interpreter.Context interpretContext = new Interpreter.Context();
            interpretContext.Input = "二十一";
            Interpreter.InterpretPrivoder interpreter = new Interpreter.InterpretPrivoder();
            interpreter.FormatStr(interpretContext);
            Console.WriteLine(interpretContext.Output);
            Console.ReadKey();

结果:

三、总结

解释器模式,实在一种模式经常出现,并不断变化。我们可以使用解释器。

缺点就是容易子类膨胀

 

posted @   K战神  阅读(212)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示