Chinaunix首页 | 论坛 | 博客
  • 博客访问: 657825
  • 博文数量: 220
  • 博客积分: 10487
  • 博客等级: 上将
  • 技术积分: 2072
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-09 00:25
文章分类

全部博文(220)

文章存档

2012年(5)

2011年(38)

2010年(135)

2009年(42)

我的朋友

分类:

2009-10-28 01:43:43

定义

给定一种语言,并定义其语法,然后用解释器解释使用该语言中的句子。

使用频度:


UML 类图



参与者

该模式参与的类或对象

  • AbstractExpression(抽象语法)
    • 定义执行操作的接口
  • TerminalExpression(终结符表达式,具体表达式ThousandExpression, HundredExpression, TenExpression, OneExpression )
    • 实现一个与语法中终结符关联的解释操作.
    • 句子中每个终结符需要一个实例.
  • NonterminalExpression(非终端表达式)
    • 语法中的每个规则R1:=R2R3...Rn都需要这样的类
    • 从R1到Rn每个符号都要维护一个AbstractExpression类型的实例变量
    • 实现非终端符号的解释操作,解释器一般要递归的调用表示从R1到Rn的解释操作
  • Context(上下文)
    • 包含解释器之外的全局信息
  • Client(客户)
    • 构建抽象语法树
    • 调用解释操作


C# 示例代码


// Interpreter pattern -- Structural example


using System;

using System.Collections;

 

namespace DoFactory.GangOfFour.Interpreter.Structural

{

  ///




  /// MainApp startup class for Structural


  /// Interpreter Design Pattern.


  ///



  class MainApp

  {

    ///


    /// Entry point into console application.


    ///



    static void Main()

    {

      Context context = new Context();

 

      // Usually a tree


      ArrayList list = new ArrayList();

 

      // Populate 'abstract syntax tree'


      list.Add(new TerminalExpression());

      list.Add(new NonterminalExpression());

      list.Add(new TerminalExpression());

      list.Add(new TerminalExpression());

 

      // Interpret


      foreach (AbstractExpression exp in list)

      {

        exp.Interpret(context);

      }

 

      // Wait for user


      Console.ReadKey();

    }

  }

 

  ///


  /// The 'Context' class


  ///



  class Context

  {

  }

 

  ///


  /// The 'AbstractExpression' abstract class


  ///



  abstract class AbstractExpression

  {

    public abstract void Interpret(Context context);

  }

 

  ///


  /// The 'TerminalExpression' class


  ///



  class TerminalExpression : AbstractExpression

  {

    public override void Interpret(Context context)

    {

      Console.WriteLine("Called Terminal.Interpret()");

    }

  }

 

  ///


  /// The 'NonterminalExpression' class


  ///



  class NonterminalExpression : AbstractExpression

  {

    public override void Interpret(Context context)

    {

      Console.WriteLine("Called Nonterminal.Interpret()");

    }

  }

}


输出


Called Terminal.Interpret()
Called Nonterminal.Interpret()
Called Terminal.Interpret()
Called Terminal.Interpret()


阅读(717) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~