本文翻译自:http://www./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类图
三、参与者
该模式的类/对象参与者包括:
AbstractExpression (描述)
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
四、示例代码
以下结构性的代码描述解释器模式,即利用一个定义好的语法,为进程解析声明提供解释器。
另外一个实例即利用解释器模式来实现如何将罗马数字跟十进制的转换,代码如下: