# Purpose
The Interpreter pattern provides a way to evaluate sentences in a language, allowing the interpretation of those sentences within the program.
Simply put: Like a translator that takes complicated instructions and turns them into simple steps we can follow.
# Problem
Need to process languages or expressions defined by grammar rules (compilers, rule engines, etc.).
# Solution
Implement a class for each grammar rule. Each rule is an expression that can be interpreted to evaluate the sentence.
# Abstract Syntax Tree (AST)
Key representation of the structure of an expression.
-
Leaf Nodes: Values or operands (numbers).
-
Internal Nodes: Operators (+, -).
# Structure
# Participants
- AbstractExpression: Declares an interpret operation.
- TerminalExpression: Interpretation for terminal symbols.
- NonTerminalExpression: Complex grammatical rules.
- Context: Global information for interpretation.
- Client: Builds the AST and invokes the interpretation.
# When to Use It
-
Languages representable as abstract syntax trees.
-
Interpreting simple notations or DSLs.
# Advantages
-
verified
Flexibility: New types of expressions.
-
verified
Extensibility: Easy to extend the grammar.
# Disadvantages
-
warning
Complexity: Difficult for heavy grammars.
-
warning
Performance: Interpretation is less efficient than compilation.
# Example: Math Expressions
Interpretation of "1 + 2". Decomposition into parts: constant, operator, constant.
# Java Code
interface Expression { int interpret(); }
class NumberExpression implements Expression {
private int number;
public int interpret() { return number; }
}
class AddExpression implements Expression {
private Expression left, right;
public int interpret() { return left.interpret() + right.interpret(); }
}
# Mapping Participants
- Expression: AbstractExpression.
- NumberExpression: TerminalExpression.
- AddExpression: NonterminalExpression.
- Client: Evaluator.
# Conclusions
Provides flexibility to build systems that need to dynamically "understand" structured inputs.
# Related Patterns
Composite
To build the abstract syntax tree.
Flyweight
To share instances of TerminalExpression.