Java设计模式--解释器模式

2018-05-09  本文已影响0人  留给时光吧

这种模式也是行为型模式,主要是对一些文法的解释。常见的有SQL解析,表达式解析。这种模式比较常见,但实现起来有一定难度,需要考虑的情况比较完善,这里简单举一个加减法计算器的例子:

解释器接口:

public interface Expression {
    int interpret();
}

具体各种解释器:

//数字解释器
public class NumExpression implements Expression{
    private int num;
    public NumExpression(int num){
        this.num = num;
    }

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

//操作符解释器抽象类
public abstract class OperatorExpression implements Expression{
    protected Expression exp1,exp2;

    public OperatorExpression(Expression exp1,Expression exp2){
        this.exp1 = exp1;
        this.exp2 = exp2;
    }

}

//加法解释器
public class AdditionExpression extends OperatorExpression{
    public AdditionExpression(Expression exp1, Expression exp2) {
        super(exp1, exp2);
    }

    @Override
    public int interpret() {
        return exp1.interpret() + exp2.interpret();
    }
}

//减法解释器
public class SubtractionExpression extends OperatorExpression{
    public SubtractionExpression(Expression exp1, Expression exp2) {
        super(exp1, exp2);
    }

    @Override
    public int interpret() {
        return exp1.interpret() - exp2.interpret();
    }
}

解释器执行者:

public class Calculator {
    private Stack<Expression> stack = new Stack<>();
    private String expression;

    public Calculator(String expression){
        this.expression = expression;
    }

    public int calculate(){
        Expression exp1,exp2;

        String[] elements = expression.split(" ");
        for (int i = 0;i<elements.length;i++){
            switch (elements[i].charAt(0)){
                case '+':
                    exp1 = stack.pop();
                    exp2 = new NumExpression(Integer.valueOf(elements[++i]));
                    stack.push(new AdditionExpression(exp1,exp2));
                    break;
                case '-':
                    exp1 = stack.pop();
                    exp2 = new NumExpression(Integer.valueOf(elements[++i]));
                    stack.push(new SubtractionExpression(exp1,exp2));
                    break;
                default:
                    stack.push(new NumExpression(Integer.valueOf(elements[i])));
                    break;
            }
        }

        return stack.pop().interpret();
    }
}

测试类

    public static void main(String[] args) {
        Calculator calculator = new Calculator("1 + 2 + 3 - 4");
        System.out.println(calculator.calculate());
    }

更复杂的比如涉及乘除法,括号,幂运算等,就要先对表达式进行转换,如转为后缀表达式,在书写对应解释器。

上一篇下一篇

猜你喜欢

热点阅读