设计模式-解释器模式

解释器模式-Interpreter Pattern

解释器模式(Interpreter Pattern):定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,这里的“语言”是指使用规定格式和语法的代码。解释器模式是一种类行为型模式。

我的理解:有一点点类似组合模式,一点点。使用非终结符作为分割,每两个或几个处理成一个终结符,最后处理成一个终结符。

抽象解释器:声明一个所有具体表达式都要实现的抽象接口(或者抽象类),接口中主要是一个interpret()方法,称为解释操作。具体解释任务由它的各个实现类来完成,具体的解释器分别由终结符解释器和非终结符解释器完成。终结符表达式:实现与文法中的元素相关联的解释操作,通常一个解释器模式中只有一个终结符表达式,但有多个实例,对应不同的终结符。终结符一半是文法中的运算单元,比如有一个简单的公式R=R1+R2,在里面R1和R2就是终结符,对应的解析R1和R2的解释器就是终结符表达式。非终结符表达式:文法中的每条规则对应于一个非终结符表达式,非终结符表达式一般是文法中的运算符或者其他关键字,比如公式R=R1+R2中,+就是非终结符,解析+的解释器就是一个非终结符表达式。非终结符表达式根据逻辑的复杂程度而增加,原则上每个文法规则都对应一个非终结符表达式。环境角色:这个角色的任务一般是用来存放文法中各个终结符所对应的具体值,比如R=R1+R2,我们给R1赋值100,给R2赋值200。这些信息需要存放到环境角色中,很多情况下我们使用Map来充当环境角色就足够了。
在个地方参考的: https://www.jianshu.com/p/c138a1d2be5e

抽象解释器:

public interface AbstractNode {
    Integer interpret();
}
非终结符表达式:

public class AndNode implements AbstractNode {
    AbstractNode left,right;

    public AndNode(AbstractNode left, AbstractNode right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public Integer interpret() {
        return left.interpret()+right.interpret();
    }
}
终结符表达式:

public class VariableNode implements AbstractNode {
    private Integer num;

    public VariableNode(Integer num) {
        this.num = num;
    }

    @Override
    public Integer interpret() {
        return num;
    }
}

处理类 使用stack做环境角色

public class Handler {

    Stack stack = new Stack();
    AbstractNode node;
    public void handler(String instruction){
        //以空格分割字符串
        String[] words = instruction.split(" ");
        for (int i = 0; i < words.length; i++) {
            if(words[i].equalsIgnoreCase("+")){
                //如果为"+" 将栈中的弹出作为左节点
                AbstractNode left = (AbstractNode) stack.pop();
                //将"+"后面的作为右节点
                AbstractNode right = new VariableNode(Integer.parseInt(words[++i]));
                //左右节点组合成一个非终结符表达式
                this.node = new AndNode(left,right);
                //组合的结果放入栈中
                stack.push(this.node);
            }else{
                //如果为数字 存入一个终结表达式
                AbstractNode abn1 = new VariableNode(Integer.parseInt(words[i]));
                //放在栈中
                stack.push(abn1);
            }
        }
        //循环结束 取出栈中结果
        this.node = (AbstractNode) stack.pop();
    }
    public Integer output() {
        Integer result = this.node.interpret(); //解释表达式
        return result;
    }
}
Client:

public class Client {

    public static void main(String[] args) {
        String instroction1 = "1 + 2 + 3 + 4";
        String instroction2 = "1 + 2 + 3";
        String instroction3 = "1 + 23";
        Handler math = new Handler();
        math.handler(instroction1);
        System.out.println(math.output());
        math.handler(instroction2);
        System.out.println(math.output());
        math.handler(instroction3);
        System.out.println(math.output());
    }
}





猜你喜欢

转载自blog.csdn.net/webmastar/article/details/79269234
今日推荐