美文网首页
解释器(Interpreter)模式

解释器(Interpreter)模式

作者: 莫库施勒 | 来源:发表于2019-08-02 19:33 被阅读0次
    public interface Expression {
       public 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 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);
       }
    }
    
    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);
       }
    }
    
    public class InterpreterPatternDemo {
     
       //规则:Robert 和 John 是男性
       public static Expression getMaleExpression(){
          Expression robert = new TerminalExpression("Robert");
          Expression john = new TerminalExpression("John");
          return new OrExpression(robert, john);    
       }
     
       //规则:Julie 是一个已婚的女性
       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"));
       }
    }
    

    相关文章

      网友评论

          本文标题:解释器(Interpreter)模式

          本文链接:https://www.haomeiwen.com/subject/yqyrdctx.html