版权声明:本文为博主原创,未经博主允许不得转载。 https://blog.csdn.net/weixin_36904568/article/details/90083833
1. 定义
给定一个语言之后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子
2. 使用
- 抽象表达式:定义解释的方法
- 终结符表达式:特殊符号
- 非终结符表达式:常量
- 上下文:存放文法中各个终结符所对应的具体值
package InterpreterPattern;
import java.util.HashMap;
import java.util.Map;
/**
* 上下文的环境,存储符号对应的整数值
*/
public class Context {
private HashMap<Variable,Integer> map;
public Context() {
this.map = new HashMap<>();
}
public void assign(Variable variable,int num){
map.put(variable,num);
}
public int lookup(Variable variable){
return map.get(variable);
}
}
package InterpreterPattern;
/**
* 抽象表达式
*/
public abstract class Exception {
//抽象的解释方法
public abstract int interpret(Context context);
}
package InterpreterPattern;
import java.util.Objects;
/**
* 终结符表达式“常量”
*/
public class Variable extends Exception{
private String name;
public Variable(String name){
this.name = name;
}
//获取符号对应的整数
@Override
public int interpret(Context context) {
return context.lookup(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Variable variable = (Variable) o;
return Objects.equals(name, variable.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
package InterpreterPattern;
/**
* 非终结符表达式“+”
*/
public class Add extends Exception{
private Exception exception1;
private Exception exception2;
public Add(Exception exception1, Exception exception2) {
this.exception1 = exception1;
this.exception2 = exception2;
}
//相加
@Override
public int interpret(Context context) {
return exception1.interpret(context)+exception2.interpret(context);
}
}
package InterpreterPattern;
public class Test {
public static void main(String[] args) {
Context context = new Context();
//声明变量
Variable a = new Variable("a");
Variable b = new Variable("b");
//赋值
context.assign(a,1);
context.assign(b,2);
//加起来
Exception exception = new Add(a,b);
System.out.println(exception.interpret(context));
}
}
3. 特点
- 容易扩展语言
- 语法规则容易扩展方法
- 可以处理脚本语言和编程语言
- 在语法规则的数目过大时,应该使用编译器或解释器的产生器