行為模式之直譯器模式
阿新 • • 發佈:2019-02-13
直譯器模式(Interpreter)為某一特定語言定義文法,併為該語言的特定上下文提供解釋。
直譯器模式包含五部分:
- AbstractExpression 宣告一個抽象的解釋操作
- TerminalExpression 終結符表示式,實現終結符的解釋操作
- NonterminalExpression 非終結符表示式,實現非終結符的解釋操作
- Context 直譯器之外的全域性資訊
- Client 構建某一語言的句子,並呼叫解釋操作
AbstractExpression
interface Expression {
boolean interpret(String context);
}
TerminalExpression
class BoolExpression implements Expression {
private String name;
public BoolExpression(String name) {
this.name = name;
}
@Override
public boolean interpret(String context) {
return context.contains(name);
}
}
NonterminalExpression
class AndExpression implements Expression {
private Expression expression1;
private Expression expression2;
public AndExpression(Expression expression1, Expression expression2) {
this.expression1 = expression1;
this.expression2 = expression2;
}
@Override
public boolean interpret(String context) {
return expression1.interpret(context) && expression2.interpret(context);
}
}
Client
class Client {
void test() {
String context = "ABCDEF";
Expression expressionABC = new BoolExpression("ABC");
Expression expressionDEF = new BoolExpression("DEF");
Expression andExpression = new AndExpression(expressionABC, expressionDEF);
andExpression.interpret(context);
}
}