1、解释器模式
给定一个语言,定义他的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的字句。
Context类是一个上下文环境类,Plus和Minus分别用来计算的实现。
实例一:
public class Context {
private int num1;
private int num2;
public Context(final int num1, final int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int getNum1() {
return this.num1;
}
public void setNum1(final int num1) {
this.num1 = num1;
}
public int getNum2() {
return this.num2;
}
public void setNum2(final int num2) {
this.num2 = num2;
}
}
public interface Expression {
public int interpreter(Context context);
}
public class Plus implements Expression {
@Override
public int interpreter(final Context context) {
return context.getNum1() + context.getNum2();
}
}
public class Minus implements Expression {
@Override
public int interpreter(final Context context) {
return context.getNum1() - context.getNum2();
}
}
模拟调用:
public static void main(final String[] args) {
final Context context = new Context(3, 10);
Expression ex = new Plus();
int result = ex.interpreter(context);
System.out.println(" result : " + result);
ex = new Minus();
result = ex.interpreter(context);
System.out.println(" minus result : " + result);
}