# 解释器模式

## 解释器模式

定义： 给分析对象定义一个语言，并定义该语言的`文法`表示，在设计一个解释器来解释语言中的`句子`

相当于用编译语言的方式来分析应用中的实例。这种模式实现了`文法`表达式处理的接口，该接口解释一个特定的上下文

* 文法：语言的语法规则
* 句子：语言集中的元素

解释器属于类行为模式，该模式在开发中很少用到

## 优缺点

优点：

* 扩展性好，通过类来表示语言的文法规则，因此可以通过继承机制来改变或者扩展文法
* 易于实现，在语法树中的每个表达式节点类是相似的，所以实现文法相对容易

缺点：

* 执行效率低：大量循环、递归
* 引起类膨胀：每条规则至少需要一个类，如果文法相对复杂，类的数量倍增
* 应用场景较少

## 编译原理中的相关概念

文法：

用于描述语言的语法结构的规则

## 结构和实现

* 抽象表达式角色：定义解释器的解释操作，主要包含解释方法interpret()
* 终结符表达式角色：是抽象表达式的子类，用来实现文法中与终结符相关的操作，文法中每个终结符都对应一个具体的终结表达式
* 非终结符表达式角色：抽象表达式的子类，实现文法中与非终结符相关的操作，文法中每条规则对应一个非终结符表达式
* 环境角色：包含各个解释器需要的数据或公共功能，用来传递被所有解释器共享的数据
* 客户端角色：分析句子或表达式转化昵称使用解释器对象描述的抽象语法树，然后调用解释器的解释方法

![](http://c.biancheng.net/uploads/allimg/181119/3-1Q119150626422.gif)

## 模拟场景

模拟公交卡刷卡时，不同地区的卡和不同人群的折扣不同

比如说，假如公交车读卡器可以判断乘客的身份，如果是A地区或者B地区的“老人” “妇女”“儿童”就可以免费乘车，其他人员乘车一次扣 1 元。

首先分析得到文法规则如下

```
<expression> ::= <city>的<person>
<city> ::= A地区|B区域
<person> ::= 老人|妇女|儿童
```

用“〈”和“〉”括住的是非终结符，没有括住的是终结符

![](https://raw.githubusercontent.com/larscheng/myImg/master/blogImg/DesignPatterns/20190719162303.png)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://larscheng.gitbook.io/mybook/design-patterns/behavioralmodel/interpretermode.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
