设计模式16:Interpreter Pattern(解释者模式)

来源:互联网 发布:软件项目开发计划 编辑:程序博客网 时间:2024/05/22 00:13

本文翻译自:http://www.dofactory.com/Patterns/PatternInterpreter.aspx

Define:Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

一、解释者模式概念

针对某一编程语言,为其语法定义一定的描述语言和解释器,解释器利用描述语言去解释该编程语言中的所有语法。

二、UML类图

 
UML

三、参与者

该模式的类/对象参与者包括:

  • AbstractExpression  (描述)
    • 为执行operation()声明一个接口
  • TerminalExpression  ( ThousandExpression, HundredExpression, TenExpression, OneExpression )
    • 在语法中使用终止符实现一个operation解释器
    • 在语句中要求所有终止符需要一个实例
  • NonterminalExpression  ( 不使用 )
    • one such class is required for every rule R ::= R1R2...Rn in the grammar
    • maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.
    • implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
  • Context  (Context)
    • 所有全局解释器的内容信息
  • Client  (InterpreterApp)
    • builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes
    • invokes the Interpret operation

    四、示例代码

    以下结构性的代码描述解释器模式,即利用一个定义好的语法,为进程解析声明提供解释器。

     

    另外一个实例即利用解释器模式来实现如何将罗马数字跟十进制的转换,代码如下:

    原创粉丝点击