设计模式之解释器模式

解释器模式:提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。

主要意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。

主要解决:对于一些固定文法构建一个解释句子的解释器。

解决方案:构建语法树,定义终结符与非终结符。

优点:

1、可扩展性比较好,灵活。

2、增加了新的解释表达式的方式。

3、易于实现简单文法。

缺点:

1、可利用场景比较少。

2、对于复杂的文法比较难维护。

3、解释器模式会引起类膨胀。

4、解释器模式采用递归调用方法。

解释器类图:

代码实现:

客户端代码:

using System;
using System.Collections.Generic;

namespace _01解释器模式_结构图
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context();
            IList<AbstractExpression> list = new List<AbstractExpression>();
            list.Add(new TerminalExpression());
            list.Add(new NonterminalExpression());
            list.Add(new TerminalExpression());
            list.Add(new TerminalExpression());

            foreach (AbstractExpression exp in list)
            {
                exp.Interpret(context);
            }
            Console.Read();
        }
    }
}

抽象解释器:

using System;
using System.Collections.Generic;
using System.Text;

namespace _01解释器模式_结构图
{
    abstract class AbstractExpression
    {
        public abstract void Interpret(Context context);
    }
}

终结符表达式:

using System;
using System.Collections.Generic;
using System.Text;

namespace _01解释器模式_结构图
{
    class TerminalExpression:AbstractExpression
    {
        public override void Interpret(Context context)
        {
            Console.WriteLine("终端解释器");
        }
    }
}

非终结符表达式:

using System;
using System.Collections.Generic;
using System.Text;

namespace _01解释器模式_结构图
{
    class NonterminalExpression:AbstractExpression
    {
        public override void Interpret(Context context)
        {
            Console.WriteLine("非终端解释器");
        }
    }
}

环境角色:

using System;
using System.Collections.Generic;
using System.Text;

namespace _01解释器模式_结构图
{
    class Context
    {
        private string input;
        public string Input
        {
            get { return input; }
            set { input = value; }
        }
        private string output;
        public string Output
        {
            get { return output; }
            set { output = value; }
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李金轩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值