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

时间:2022-03-15 17:08:49

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

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

解释器模式是个不怎么常用的设计模式。我们先来举一个简单的例子说明它。

a+b-c这么一个表达式,+,-都是非终结符表达式,a,b,c都是终结符表达式非终结表达式一般是文法中的运算符或者关键字,而终结表达式一般是文法中的运算单元

package interpreter;

import java.util.HashMap;
import java.util.Map;

public class Context {
private final Map<String, Integer> valueMap = new HashMap<String, Integer>();

public void addValue(final String key, final int value) {
valueMap.put(key, Integer.valueOf(value));
}

public int getValue(final String key) {
return valueMap.get(key).intValue();
}
}
package interpreter;public abstract class AbstractExpression {public abstract int interpreter(Context context);}
package interpreter;public class AddNonterminalExpression extends AbstractExpression {    private final AbstractExpression left;    private final AbstractExpression right;    public AddNonterminalExpression(final AbstractExpression left, final AbstractExpression right) {        this.left = left;        this.right = right;    }    @Override    public int interpreter(final Context context) {        return this.left.interpreter(context) + this.right.interpreter(context);    }}
package interpreter;public class SubtractNonterminalExpression extends AbstractExpression {    private final AbstractExpression left;    private final AbstractExpression right;    public SubtractNonterminalExpression(final AbstractExpression left, final AbstractExpression right) {        this.left = left;        this.right = right;    }    @Override    public int interpreter(final Context context) {        return this.left.interpreter(context) - this.right.interpreter(context);    }}
package interpreter;public class TerminalExpression extends AbstractExpression {    private final int i;    public TerminalExpression(final int i) {        this.i = i;    }    @Override    public int interpreter(final Context context) {        return this.i;    }}
package interpreter;import flyweight.Flyweight;import flyweight.FlyweightFactory;import flyweight.UnsharedFlyweight;public class Client {public static void main(String[] args) {// TODO Auto-generated method stub//a+b-cfinal Context context = new Context();        context.addValue("a", 7);        context.addValue("b", 8);        context.addValue("c", 2);        final AddNonterminalExpression addValue = new AddNonterminalExpression        (new TerminalExpression(context.getValue("a")),  new TerminalExpression(context.getValue("b")));        final SubtractNonterminalExpression subtractValue = new SubtractNonterminalExpression        (addValue,  new TerminalExpression(context.getValue("c")));        System.out.println(subtractValue.interpreter(context));}}
解释器模式的优缺点

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

解释器模式的应用场景和注意事项
设计模式之---解释器模式