Interpreter Design Pattern
Interpreter Design Pattern
1. AbstractExpression
2. TerminalExpression
3. NonterminalExpression
4. Context
5. Client
The client is responsible for creating the abstract syntax tree (AST) and
invoking the interpret() method on the root of the tree. The AST is
typically created by parsing the input language and constructing a
hierarchical representation of the expressions.
6. Interpreter
Expression Evaluation:
Combining Interpretations:
1. Client
The client provides input expressions and interacts with the
interpreter.
Java
// Create interpreter
Context context = new Context();
Interpreter interpreter = new Interpreter(context);
// Interpret expression
int result = interpreter.interpret(expression);
System.out.println("Result: " + result);
}
}
2. Context
The context holds global information needed for interpretation.
Java
3. Abstract Expression
Defines the common interface for interpreting expressions.
Java
4. Terminal Expression
Represents basic language elements.
Java
@Override
public int interpret(Context context) {
return number;
}
}
5. Non-Terminal Expression
Represents composite language constructs.
Java
@Override
public int interpret(Context context) {
return left.interpret(context) + right.interpret(context);
}
}
@Override
public int interpret(Context context) {
return left.interpret(context) * right.interpret(context);
}
}
class Context {
// Any global information needed for interpretation
}
interface Expression {
int interpret(Context context);
}
class NumberExpression implements Expression {
private int number;
class Interpreter {
private Context context;
// Create interpreter
Context context = new Context();
Interpreter interpreter = new Interpreter(context);
// Interpret expression
int result = interpreter.interpret(expression);
System.out.println("Result: " + result);
}
}
Output
Result: 14