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

本文翻译自: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

    四、示例代码

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

     

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值