---
title: "解释器模式（Interpreter）"
author: "ldaolong"
date: "2014-10-21T14:24:55Z"
tags: []
categories: ["非技术"]
slug: "interpreter"
draft: false
lastmod: "2014-10-21T14:24:55Z"
id: 2142610
url: "https://ldaolong.iteye.com/blog/2142610"
---

一、核心思想

是一个特殊的设计模式。它建立一个解释器，对于特定的计算机程序设计语言，用来解释预先定义的文法。

简单的说就是一种简单的语法解释器架构。

包括三个类：

上下文环境类Context：

解释器接口Expression：

解释器具体实现类：

 

![](http://dl.iteye.com/upload/attachment/0083/1231/c87e402e-a355-3761-9ce3-7978956ba475.jpg)

Context类是一个上下文环境类，Plus和Minus分别是用来计算的实现

 

Codes:

 

1. public interface Expression {
2. public int interpret(Context context);
3. }

 

1. public class Plus implements Expression {
2. @Override
3. public int interpret(Context context) {
4. return context.getNum1()+context.getNum2();
5. }
6. }

 

1. public class Minus implements Expression {
2. @Override
3. public int interpret(Context context) {
4. return context.getNum1()-context.getNum2();
5. }
6. }

 

01. public class Context {
02. private int num1;
03. private int num2;
04. public Context(int num1, int num2) {
05. this.num1 = num1;
06. this.num2 = num2;
07. }
08. public int getNum1() {
09. return num1;
10. }
11. public void setNum1(int num1) {
12. this.num1 = num1;
13. }
14. public int getNum2() {
15. return num2;
16. }
17. public void setNum2(int num2) {
18. this.num2 = num2;
19. }
20. }

 

1. public class Test {
2. public static void main(String\[] args) {
3. // 计算9+2-8的值
4. int result = new Minus().interpret((new Context(new Plus()
5. .interpret(new Context(9, 2)), 8)));
6. System.out.println(result);
7. }
8. }

最后输出正确的结果：3。

 

二、何时使用

描述了如何构成一个简单的语言解释器，主要应用在使用面向对象语言开发编译器中。

适用面比较窄。

 

三、Java 中的应用

Java正则表达式解析器Pattern