本文共 2513 字,大约阅读时间需要 8 分钟。
解释器模式是软件架构中的一个行为型模式,用于定义语言的文法表示,并提供解释句子的解释器,使客户端能够通过解释器解释语言中的句子。
解释器模式的主要意图是为给定的语言定义其文法表示,并提供一个解释句子的解释器。这个解释器可以通过解释表达式来理解语言中的句子。
解释器模式主要解决以下问题:对于一些固定文法,需要构建一个解释句子的解释器。
public abstract class Expression { public abstract boolean interpret(Context ctx); public abstract boolean equals(Object o); public abstract int hashCode(); public abstract String toString();} public class Constant extends Expression { private boolean value; public Constant(boolean value) { this.value = value; } @Override public boolean interpret(Context ctx) { return value; } @Override public String toString() { return new Boolean(value).toString(); }} public class And extends Expression { private Expression left, right; public And(Expression left, Expression right) { this.left = left; this.right = right; } @Override public boolean interpret(Context ctx) { return left.interpret(ctx) && right.interpret(ctx); } @Override public String toString() { return "(" + left.toString() + " AND " + right.toString() + ")"; }} public class Context { private Map map = new HashMap<>(); public void assign(Variable var, boolean value) { map.put(var, new Boolean(value)); } public boolean lookup(Variable var) { Boolean value = map.get(var); return value != null ? value : false; }} public class Client { private static Context ctx; private static Expression exp; public static void main(String[] args) { ctx = new Context(); Variable x = new Variable("x"); Variable y = new Variable("y"); Constant c = new Constant(true); ctx.assign(x, false); ctx.assign(y, true); exp = new Or(new And(c, x), new And(y, new Not(x))); System.out.println("x = " + x.interpret(ctx)); System.out.println("y = " + y.interpret(ctx)); System.out.println(exp.toString() + " = " + exp.interpret(ctx)); }} 转载地址:http://pliuz.baihongyu.com/