首页 > 代码库 > 设计模式18---解释器模式

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

解释器模式常用的场景是计算器,或者说公式。

也就是说解释的符号满足公式的元素,而client端把每个元素的内容代换掉就可以。

技术分享

package com.jayfulmath.designpattern.experssion;import java.util.HashMap;public abstract class Experssion {    //解析公式和数值,其中var中的key值是是公式中的参数,value值是具体的数字    public abstract int interpreter(HashMap<String, Integer> var);}
package com.jayfulmath.designpattern.experssion;import java.util.HashMap;public class VarExperssion extends Experssion {    private String key;    @Override    public int interpreter(HashMap<String, Integer> var) {        System.out.println("VarExperssion interpreter key:"+key);        return var.get(key);    }    public VarExperssion(String key) {        super();        this.key = key;    }        }
public abstract class  SymbolExperssion extends Experssion {    Experssion left;    Experssion right;    public SymbolExperssion(Experssion left, Experssion right) {        super();        this.left = left;        this.right = right;    }    }
import java.util.HashMap;public class AddExperssion extends SymbolExperssion {    public AddExperssion(Experssion left, Experssion right) {        super(left, right);            }    @Override    public int interpreter(HashMap<String, Integer> var) {        return super.left.interpreter(var)+super.right.interpreter(var);    }    }
package com.jayfulmath.designpattern.experssion;import java.util.HashMap;public class SubExperssion extends SymbolExperssion {    public SubExperssion(Experssion left, Experssion right) {        super(left, right);            }    @Override    public int interpreter(HashMap<String, Integer> var) {        return super.left.interpreter(var) - super.right.interpreter(var);    }}

 

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