zoukankan      html  css  js  c++  java
  • interpreter

    解释器模式:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

    如果一个特定的类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言中的句子。这样可以构造一个解释器,该解释器通过解释这些句子来解决该问题。当有一个语言需要解释,并且你可以将该语言中的句子表示为一个抽象语法树,可使用解释器模式。

    好处:容易地改变和扩展文法,因为该模式使用类来表示文法规则,你可以使用继承来改变或扩展该文法,也比较容易实现文法。因为定义抽象语法树中的各个节点的类的实现都大体相似,这些类易于直接编写。

    不足:解释器模式为每个规则至少定义了一个类,因此包含许多规则的文法可能难以管理和维护。

    Context:包含解释器外的一些全局信息。

    Expression:抽象表达式,声明一个抽象的解释操作。这个接口为抽象语法树中所有节点共享。

    ContextExpression:具体的解释器,根据Context的内容分别作出不同的解释。

    class Context {
    
        private String input;
    
        private String output;
    
        public String getInput() {
            return input;
        }
    
        public void setInput(String input) {
            this.input = input;
        }
    
        public String getOutput() {
            return output;
        }
    
        public void setOutput(String output) {
            this.output = output;
        }
    
    }
    public abstract class Expression {
    
        public abstract void interpret(Context context);
    
    }
    class ConcreteExpression1 extends Expression {
    
        @Override
        public void interpret(Context context) {
            try {
                Double.parseDouble(context.getInput());
                System.out.println("it's a number.");
            }
            catch (Exception e) {
                System.out.println("it's a string.");
            }
        }
    
    }
    
    class ConcreteExpression2 extends Expression {
    
        @Override
        public void interpret(Context context) {
            double score = Double.parseDouble(context.getInput());
            if (score < 60) {
                System.out.println("不合格!");
            }
            else {
                System.out.println("合格!");
            }
        }
    
    }
        public static void main(String[] args) {
            
            Expression e1 = new ConcreteExpression1();
            
            Expression e2 = new ConcreteExpression2();
            
            Context context = new Context();
            context.setInput("98");
            
            e1.interpret(context);
            e2.interpret(context);
            
        }

    打印结果:
    it's a number.
    合格!

  • 相关阅读:
    ZOJ3513_Human or Pig
    ZOJ2083_Win the Game
    ZOJ2725_Digital Deletions
    ZOJ2686_Cycle Gameu
    UVALive
    ZOJ2290_Game
    ZOJ3067_Nim
    P3159 [CQOI2012]交换棋子(费用流)
    P3153 [CQOI2009]跳舞(最大流多重匹配)
    P3121 [USACO15FEB]审查(黄金)Censoring (Gold)(ac自动机)
  • 原文地址:https://www.cnblogs.com/xuekyo/p/2625609.html
Copyright © 2011-2022 走看看