Skip to content

解释器(Interpreter)模式 行为型模式

提供如何定义语言的文法,以及对语言句子的解释方法,即解释器。

c#
// 解释器模式示例
using System;

// 定义一个抽象表达式类,用于解释语言中的各种表达式
abstract class Expression
{
    public abstract bool Interpret(string context);
}

// 定义一个终结符表达式类,用于解释语言中的终结符表达式
class TerminalExpression : Expression
{
    private string _data;

    public TerminalExpression(string data)
    {
        _data = data;
    }

    public override bool Interpret(string context)
    {
        if (context.Contains(_data))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

// 定义一个非终结符表达式类,用于解释语言中的非终结符表达式
class NonterminalExpression : Expression
{
    private Expression _expression1;
    private Expression _expression2;

    public NonterminalExpression(Expression expression1, Expression expression2)
    {
        _expression1 = expression1;
        _expression2 = expression2;
    }

    public override bool Interpret(string context)
    {
        return _expression1.Interpret(context) && _expression2.Interpret(context);
    }
}

// 定义一个上下文类,用于存储解释器解释的上下文信息
class Context
{
    private string _context;

    public Context(string context)
    {
        _context = context;
    }

    public string GetContext()
    {
        return _context;
    }

    public void SetContext(string context)
    {
        _context = context;
    }
}

// 定义一个客户端类,用于测试解释器模式
class InterpreterPatternDemo
{
    static void Main(string[] args)
    {
        // 定义上下文信息
        Context context = new Context("Hello World");

        // 定义终结符表达式
        Expression terminalExpression = new TerminalExpression("Hello");

        // 定义非终结符表达式
        Expression nonterminalExpression = new NonterminalExpression(new TerminalExpression("Hello"), new TerminalExpression("World"));

        // 输出解释结果
        Console.WriteLine(terminalExpression.Interpret(context.GetContext()));
        Console.WriteLine(nonterminalExpression.Interpret(context.GetContext()));

        Console.ReadKey();
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度