解释器模式(Interpreter)提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等
核心:
优点:
缺点:
使用场景:
注意事项:1、可利用场景比较少,JAVA 中如果碰到可以用 expression4J 代替
public interface Expression { boolean interpreter(String Context); }
public class TerminalExpression implements Expression { private String date ; public TerminalExpression(String date) { this.date = date; } @Override public boolean interpreter(String Context) { if(Context.contains(date)) { return true; } return false; } } public class AndExpression implements Expression { private Expression e1; private Expression e2; public AndExpression(Expression e1, Expression e2) { this.e1 = e1; this.e2 = e2; } @Override public boolean interpreter(String Context) { return e1.interpreter(Context) && e2.interpreter(Context); } } public class OrExpression implements Expression{ private Expression e1; private Expression e2; public OrExpression(Expression e1, Expression e2) { this.e1 = e1; this.e2 = e2; } @Override public boolean interpreter(String Context) { return e1.interpreter(Context) || e2.interpreter(Context); } }
public class InterpretDemo { //规则:Vicent 和 John 是男性 public static Expression isMale() { Expression e1 = new TerminalExpression("Vicent"); Expression e2 = new TerminalExpression("John"); return new OrExpression(e1, e2); } //规则:Forry 是一个已婚的女性 public static Expression isMarried() { Expression e1 = new TerminalExpression("Forry"); Expression e2 = new TerminalExpression("Married"); return new AndExpression(e1, e2); } public static void main(String[] args) { Expression isMale = isMale(); Expression isMarriedWoman = isMarried(); System.out.println("John is male? " + isMale.interpreter("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpreter("Married Julie")); } }
原文:https://www.cnblogs.com/vincentYw/p/12675190.html