解释器模式:为语言创建解释器,提供评估语言的语法或表达式的方法。
例子:
public interface Expression { public abstract boolean interpret(String context); } public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data) { this.data = data; } @Override public boolean interpret(String context) { if(context.contains(data)) { return true; } return false; } } public class OrExpression implements Expression { private Expression exp1; private Expression exp2; public OrExpression(Expression exp1, Expression exp2) { this.exp1 = exp1; this.exp2 = exp2; } @Override public boolean interpret(String context) { return exp1.interpret(context) || exp2.interpret(context); } } public class AndExpression implements Expression { private Expression exp1; private Expression exp2; public AndExpression(Expression exp1, Expression exp2) { this.exp1 = exp1; this.exp2 = exp2; } @Override public boolean interpret(String context) { return exp1.interpret(context) && exp2.interpret(context); } } public class Test { public static Expression getMaleExpression() { Expression robert = new TerminalExpression("robert"); Expression john = new TerminalExpression("john"); return new OrExpression(robert, john); } public static Expression getMarriedWomanExpression() { Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); return new AndExpression(julie,married); } public static void main(String[] args) { Expression isMale = getMaleExpression(); System.out.println(isMale.interpret("john")); Expression isMarriedWoman = getMarriedWomanExpression(); System.out.println(isMarriedWoman.interpret("Married Julie")); } }
测试结果:
在JAVA中,使用解释器模式的地方很少,expression4j框架是基于Java的开源框架,它用于对数学表达式进行操作,是一个数学公式解析器。它是应用解释器模式的最佳例子,但目前这个框架仍在完善的过程中。
时间: 2024-10-25 06:56:53