解释器模式(Interpreter Pattern):定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,这里的“语言”是指使用规定格式和语法的代码。解释器模式是一种类行为型模式
public class Context { private String before; private String after; public String getBefore() { return before; } public void setBefore(String before) { this.before = before; } public String getAfter() { return after; } public void setAfter(String after) { this.after = after; } }
public abstract class AbstractExpression { abstract void Interpret(Context context); }
public class TerminalExpression extends AbstractExpression { @Override void Interpret(Context context) { String before = context.getBefore(); context.setAfter("被终端处理后:" + before); System.out.println(context.getAfter()); } }
public class NonterminalExpression extends AbstractExpression { @Override void Interpret(Context context) { String before = context.getBefore(); context.setAfter("被非终端处理后:" + before); System.out.println(context.getAfter()); } }
public class Interpreter01Test { public static void main(String[] args) { Context context = new Context(); context.setBefore("test"); TerminalExpression terminalExpression = new TerminalExpression(); terminalExpression.Interpret(context); NonterminalExpression nonterminalExpression = new NonterminalExpression(); nonterminalExpression.Interpret(context); /** * 被终端处理后:test * 被非终端处理后:test */ } }
优点
缺点
适用场景
应用场景