解釋器模式(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 */ } }
優勢java
缺點正則表達式
適用場景ide
應用場景測試