zoukankan      html  css  js  c++  java
  • 解释器模式

    描述

    解释器模式提供了语言的语法或者表达式的评估方式,这种模式提供一个解释特定上下文的接口。

    实例

    一个很简单的例子,检测一个查询语句,那么必须是“select from”,单独的select和from都是返回false的,都可能是其他语句,这就是and检测;同样的,检测一条更改数据库的语句那可能是insert也可能是update,那么不管检测到这两项中的哪一项都是正确的,返回true。

    实例代码如下:

    //创建一个检测类的接口
    interface Expression {
      public boolean evaluate(String context);
    }
    
    class IsInExpression implements Expression {
      private String data;
    
      public IsInExpression(String data) {
        this.data = data;
      }
      //检测函数 
      @Override
      public boolean evaluate(String context) {
        if (context.contains(data)) {
          return true;
        }
        return false;
      }
    }
    
    //两两联合检测,or检测:当有一项符合条件即返回true
    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 evaluate(String context) {
        return expr1.evaluate(context) || expr2.evaluate(context);
      }
    }
    
    //两两联合检测,and检测:当两项都符合时候才可以返回true
    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 evaluate(String context) {
        return expr1.evaluate(context) && expr2.evaluate(context);
      }
    }
    
    public class Main {
    
      public static void main(String[] args) {
        Expression select = new IsInExpression("Select");
        Expression from = new IsInExpression("From");
        Expression isSelectFrom = new AndExpression(select, from);
    
        Expression insert = new IsInExpression("Insert");
        Expression update = new IsInExpression("Update");
        Expression isInsertOrUpdate = new OrExpression(insert, update);
    
        System.out.println(isSelectFrom.evaluate("Select"));
        System.out.println(isInsertOrUpdate.evaluate("Insert"));
    
        System.out.println(isSelectFrom.evaluate("Select From"));
        System.out.println(isInsertOrUpdate.evaluate("Update"));
      }
    }
    

    测试结果:

    代码来源:特别感谢 w3school java编程模式之解释器模式

  • 相关阅读:
    第四届蓝桥杯JavaC组国(决)赛真题
    第四届蓝桥杯JavaC组国(决)赛真题
    第四届蓝桥杯JavaC组国(决)赛真题
    第四届蓝桥杯C++B组国(决)赛真题
    第四届蓝桥杯C++B组国(决)赛真题
    第四届蓝桥杯C++B组国(决)赛真题
    第四届蓝桥杯C++B组国(决)赛真题
    Qt 动画快速入门(一)
    越败越战,愈挫愈勇(人生就像心电图,一帆风顺,你就挂了!)
    CSS 编码中超级有用的工具集合
  • 原文地址:https://www.cnblogs.com/K-artorias/p/7927812.html
Copyright © 2011-2022 走看看