GoF pattern • Behavioral
GoFBehavioralJava example
Interpreter solves a specific structural problem in the design.
Represent and evaluate a small language or expression grammar.
Pattern overview
GoF pattern
Represent and evaluate a small language or expression grammar.
Intent
Given a language, define its grammar representation and an interpreter that evaluates sentences in that language.
Problem
A small domain language or rule syntax must be evaluated repeatedly inside the application.
Solution
Model grammar elements as objects and evaluate them against a context.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- For small rule engines, filters, query fragments, or DSL-like expressions.
Tradeoffs
- Does not scale well to large or complex grammars.
- Parser libraries are better for richer languages.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface Expression {
boolean interpret(Map<String, String> context);
}
record Equals(String key, String expected) implements Expression {
public boolean interpret(Map<String, String> context) {
return expected.equals(context.get(key));
}
}
record And(Expression left, Expression right) implements Expression {
public boolean interpret(Map<String, String> context) {
return left.interpret(context) && right.interpret(context);
}
}