目录

设计模式 - 解释器模式( Interpreter Pattern)

解释器模式提供了一种评估语言语法或表达的方法。 这种模式属于行为模式。 此模式涉及实现表达式接口,该接口用于解释特定上下文。 此模式用于SQL解析,符号处理引擎等。

实现 (Implementation)

我们将创建一个接口Expression和实现Expression接口的具体类。 定义了一个类TerminalExpression ,它充当相关上下文的主要解释器。 其他类OrExpressionAndExpression用于创建组合表达式。

InterpreterPatternDemo是我们的演示类,它将使用Expression类来创建规则并演示表达式的解析。

解释器模式UML图

Step 1

创建表达式界面。

Expression.java

public interface Expression {
   public boolean interpret(String context);
}

Step 2

创建实现上述接口的具体类。

TerminalExpression.java

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;
   }
}

OrExpression.java

public class OrExpression implements Expression {
   private Expression expr1 = null;
   private Expression expr2 = null;
   public OrExpression(Expression expr1, Expression expr2) { 
      this.expr1 = expr1;
      this.expr2 = expr2;
   }
   @Override
   public boolean interpret(String context) {		
      return expr1.interpret(context) || expr2.interpret(context);
   }
}

AndExpression.java

public class AndExpression implements Expression {
   private Expression expr1 = null;
   private Expression expr2 = null;
   public AndExpression(Expression expr1, Expression expr2) { 
      this.expr1 = expr1;
      this.expr2 = expr2;
   }
   @Override
   public boolean interpret(String context) {		
      return expr1.interpret(context) && expr2.interpret(context);
   }
}

Step 3

InterpreterPatternDemo使用Expression类创建规则,然后解析它们。

InterpreterPatternDemo.java

public class InterpreterPatternDemo {
   //Rule: Robert and John are male
   public static Expression getMaleExpression(){
      Expression robert = new TerminalExpression("Robert");
      Expression john = new TerminalExpression("John");
      return new OrExpression(robert, john);		
   }
   //Rule: Julie is a married women
   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();
      Expression isMarriedWoman = getMarriedWomanExpression();
      System.out.println("John is male? " + isMale.interpret("John"));
      System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie"));
   }
}

Step 4

验证输出。

John is male? true
Julie is a married women? true
↑回到顶部↑
WIKI教程 @2018