解释器模式

模式定义

解释器模式(Interpreter Pattern)提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。

模式简单案例

public abstract class Expression {
    abstract int interpret();
}
public class NumExpression extends Expression{
    int num;
    
    public NumExpression(int num) {
        this.num = num;
    }

    @Override
    int interpret() {
        return num;
    }

}
public abstract class OperatorExpression extends Expression{
    Expression exp1,exp2;

    public OperatorExpression(Expression exp1, Expression exp2) {
        super();
        this.exp1 = exp1;
        this.exp2 = exp2;
    }
}
public class AddExpression extends OperatorExpression {

    public AddExpression(Expression exp1, Expression exp2) {
        super(exp1, exp2);
    }

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

}

public class Calculator {
    Stack expStack = new Stack<>();

    public Calculator(String exp) {
        Expression exp1, exp2;
        String[] elements = exp.split(" ");
        for (int i = 0; i < elements.length; i++) {
            System.out.println(i);
            switch (elements[i].charAt(0)) {
            case '+':
                exp1 = expStack.pop();

                exp2 = new NumExpression(Integer.valueOf(elements[++i]));
                expStack.push(new AddExpression(exp1, exp2));
                break;
            default:
                expStack.push(new NumExpression(Integer.valueOf(elements[i])));
                break;
            }
        }
    }
    
    public int calculator() {
        return expStack.pop().interpret();
    }
}

public class Client {
    public static void main(String[] args) {
        System.out.println(new Calculator("10 + 2 + 10 + 2 + 10 + 30").calculator());
    }
}

你可能感兴趣的:(解释器模式)