What is the core idea of the Interpreter pattern?
The core idea of the Interpreter pattern is to describe the grammar of a simple language (or data format) and implement an interpreter that can execute expressions of that language, turning them into program actions.
1. The Essence
The pattern lets you build mini-languages inside a program - a set of rules, expressions, and operations that can be read, parsed, and executed.
Each grammar rule is represented by a class that implements a common interpret(Context) interface.
Combining these classes lets you build expression trees that are interpreted (executed) dynamically.
In other words: Interpreter turns text or symbolic expressions into an executable tree.
2. When It's Used
- When you need to process expressions according to given rules (formulas, filters, scripts, conditions).
- When the grammar is small and stable.
- When you need to let the user define commands or logic as text.
3. Structure
- AbstractExpression - a common interface with an
interpret(Context)method. - TerminalExpression - an elementary expression (a number, a variable).
- NonTerminalExpression - a compound expression (operations, combinations).
- Context - holds the data needed for interpretation (variables, environment).
- Client - builds the expression tree and triggers interpretation.
4. Example (Java)
An interpreter for simple math expressions:
interface Expression {
int interpret();
}
class NumberExpression implements Expression {
private int number;
public NumberExpression(int number) { this.number = number; }
public int interpret() { return number; }
}
class AddExpression implements Expression {
private Expression left, right;
public AddExpression(Expression left, Expression right) {
this.left = left; this.right = right;
}
public int interpret() { return left.interpret() + right.interpret(); }
}Usage:
Expression expr = new AddExpression(
new NumberExpression(5),
new AddExpression(new NumberExpression(2), new NumberExpression(3))
);
System.out.println(expr.interpret()); // 105. Advantages
- Lets you create your own languages and rules without rewriting code.
- Easy to add new expression types (new classes).
- The expression code becomes structured and extensible.
6. Disadvantages
- The number of classes grows quickly for complex grammars.
- Suitable only for simple languages (otherwise, use parsers, ANTLR, etc.).
Conclusion
The Interpreter pattern lets a program understand and execute expressions written in a "mini-language", describing each grammar rule as a separate class and building an executable expression tree.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.