32 lines
1.6 KiB
Markdown
32 lines
1.6 KiB
Markdown
# Interpreter Design Pattern — Java Example
|
|
|
|
**Pattern:** Behavioral → Interpreter
|
|
**Article:** https://ankurm.com/interpreter-design-pattern-java/
|
|
|
|
## What this example shows
|
|
|
|
A math expression evaluator built as an abstract syntax tree. `Expression` declares `interpret()` — every AST node implements it. `NumberExpression` is the only terminal: a leaf with no children that returns its value directly. `AddExpression`, `SubtractExpression`, and `MultiplyExpression` are non-terminals: each holds two child expressions and applies its operator after recursively interpreting them. `Main` is the client — it assembles three small trees by hand (`(5 + 3) * 2`, `10 - (4 + 2)`, `(3 * 4) + (10 - 6)`) and evaluates each by calling `interpret()` on the root.
|
|
|
|
## How to run
|
|
|
|
```bash
|
|
javac interpreter/*.java -d out/interpreter
|
|
java -cp out/interpreter interpreter.Main
|
|
```
|
|
|
|
Requires Java 25.
|
|
|
|
## Post Section ↔ File Mapping
|
|
|
|
| Post Section | File(s) |
|
|
|---|---|
|
|
| Implementation: Math Expression Evaluator — the AbstractExpression | `Expression.java` |
|
|
| Implementation: Math Expression Evaluator — the TerminalExpression | `NumberExpression.java` |
|
|
| Implementation: Math Expression Evaluator — AddExpression | `AddExpression.java` |
|
|
| Implementation: Math Expression Evaluator — SubtractExpression | `SubtractExpression.java` |
|
|
| Implementation: Math Expression Evaluator — MultiplyExpression | `MultiplyExpression.java` |
|
|
| Implementation: Math Expression Evaluator — wiring it together | `Main.java` |
|
|
|
|
Article: https://ankurm.com/interpreter-design-pattern-java/
|
|
All patterns: https://ankurm.com/design-patterns-java/
|