解释器模式,简单来讲就是一个简版的编译器,如果一种特定类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言中的句子。解释器模式能对一些较频率执行的文法转换为一种特定的文法类型,不过解释器模式也有其不足,就是如果文法较为复杂的话,就得需要将每一个文法转换成至少一个类,如果包含许多规则的文法可能难以维护和管理。这个时候就需要其他的技术,就是我们最开始提到的语法分析程序或编译器来处理。
解释器模式的基本类结构图很简单,最基本的实现也很简单。

1 package day_13_interpreter;
2
3 /**
4 * 包含解释器之外的一些全局信息,或者说这就是解释器要解释得文法
5 * @author 余林丰
6 *
7 * 2016年10月13日
8 */
9 public class Context {
10
11 } 1 package day_13_interpreter;
2
3 /**
4 * 解释器接口
5 * @author 余林丰
6 *
7 * 2016年10月13日
8 */
9 public interface IExpression {
10 void interpret(Context context);
11 } 1 package day_13_interpreter;
2
3 /**
4 * 非终结符表达式,为文法中的非终结符实现解释操作。对每一条规则都要有一个非终结符表达式。
5 * @author 余林丰
6 *
7 * 2016年10月13日
8 */
9 public class NonterminalExpression implements IExpression {
10
11 /* (non-Javadoc)
12 * @see day_13_interpreter.IExpression#interpret(day_13_interpreter.Context)
13 */
14 @Override
15 public void interpret(Context context) {
16 System.out.println("非终结符解释器");
17 }
18
19 } 1 package day_13_interpreter;
2
3 /**
4 * 终结符表达式,实现与文法中的终结符相关联的解释操作
5 * @author 余林丰
6 *
7 * 2016年10月13日
8 */
9 public class TerminalExpression implements IExpression {
10
11 /* (non-Javadoc)
12 * @see day_13_interpreter.IExpression#interpret(day_13_interpreter.Context)
13 */
14 @Override
15 public void interpret(Context context) {
16 System.out.println("终结符解释器");
17 }
18
19 } 1 package day_13_interpreter;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 /**
7 * @author 余林丰
8 *
9 * 2016年10月13日
10 */
11 public class Client {
12
13 public static void main(String[] args){
14 Context context = new Context();
15 List<IExpression> list = new ArrayList<IExpression>();
16 list.add(new TerminalExpression());
17 list.add(new NonterminalExpression());
18 list.add(new TerminalExpression());
19 list.add(new TerminalExpression());
20
21 for (IExpression expression : list){
22 expression.interpret(context);
23 }
24 }
25
26 }