zoukankan      html  css  js  c++  java
  • 解释器模式(Interpreter Pattern)

    解释器模式:为语言创建解释器,提供评估语言的语法或表达式的方法。

    例子:

    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的开源框架,它用于对数学表达式进行操作,是一个数学公式解析器。它是应用解释器模式的最佳例子,但目前这个框架仍在完善的过程中。

  • 相关阅读:
    List接口的实现类
    Java 容器概述
    PayPal支付接口方式(checkout)集成
    Java Bio、Nio、Aio区别
    Java Aio
    Java Nio
    Java Bio
    Java Io流
    Java 23种设计模式
    SQL检测超时工具类
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5597209.html
Copyright © 2011-2022 走看看