跳至主要內容

设计模式-行为型-解释器模式

引领潮流大约 1 分钟设计模式archive

1、定义

解释器模式:定义一个语言,定义它的文法的一种表示,并定义一个解释器

写法

/**
 * 计算
 */
public interface IArithemticExpression {
    //计算
    int interpreter();
}

/**
 * 数字
 */
public class NumExpression implements IArithemticExpression{

    private int num;

    public NumExpression(int num){
        this.num = num;
    }

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

}

/**
 * 加法
 */
public class AdditionExpression implements IArithemticExpression{

    private IArithemticExpression exp1,exp2;

    public AdditionExpression(IArithemticExpression exp1,IArithemticExpression exp2){
        this.exp1 = exp1;
        this.exp2 = exp2;
    }

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

/**
 * 减法
 */
public class SubtractionExpression implements IArithemticExpression{

    private IArithemticExpression exp1,exp2;

    public SubtractionExpression(IArithemticExpression exp1, IArithemticExpression exp2){
        this.exp1 = exp1;
        this.exp2 = exp2;
    }

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

public class Calculator implements IArithemticExpression{

    private Stack<IArithemticExpression> mExpStack = new Stack<>();

    public Calculator(String expression){

        String[] elements = expression.split(" ");

        for(int i= 0 ;i < elements.length;i++){

            switch (elements[i].charAt(0)){

                case '+':
                    IArithemticExpression exp1 = mExpStack.pop();
                    IArithemticExpression exp2 = new NumExpression(Integer.parseInt(elements[++i]));
                    mExpStack.push( new AdditionExpression( exp1,exp2 ) );
                    break;

                case '-':
                    IArithemticExpression exp3 = mExpStack.pop();
                    IArithemticExpression exp4 = new NumExpression(Integer.parseInt(elements[++i]));
                    mExpStack.push( new SubtractionExpression( exp3,exp4 ) );
                    break;

                default:
                    mExpStack.push(new NumExpression(Integer.valueOf(elements[i])));
                    break;

            }

        }

    }

    /**
     * 计算
     * @return
     */
    @Override
    public int interpreter() {
        int tmp = 0;
        for (IArithemticExpression exp : mExpStack){
            tmp = tmp + exp.interpreter();
        }
        return tmp;
    }
}

/**
 *
 * 解释器模式
 * 计算器 文法分析
 * 1、词法分析
 * 2、计算策略
 * 解释与执行分离
 *
 */
public class TestMain {

    public static void main(String[] args) {

        //计算器
        Calculator calculator = new Calculator( "1 + 2 - 5 + 6 + 7" );
        calculator.interpreter();

    }

}

代码示例

https://github.com/yinlingchaoliu/23-design-pattern