Interpreter
Part of the original GoF book; refactoring.guru omits it from its catalog.
Intent
Defines a grammar for a simple language and an interpreter that evaluates sentences in it.
Problem
Users need to write small rules or expressions (filters, formulas) that the app evaluates.
Solution
Represent each grammar rule as a class; build an abstract syntax tree and evaluate it recursively.
Real-world analogy
A musician reading sheet music: the notation is a small language that gets interpreted into sound.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1AbstractExpression — Abstract Expression declares interpret().
- 2TerminalExpression — Terminal Expressions handle literals and variables.
- 3NonterminalExpression — Nonterminal Expressions represent grammar rules built from other expressions.
- 4Context — Context holds information shared during interpretation, such as variable values.
Code example
Applicability
Use Interpreter when the grammar is simple and efficiency is not critical.
Pros and cons
Pros
- Easy to change and extend the grammar
Cons
- Complex grammars become hard to maintain; prefer a parser generator
Check yourself
Users type rules like price > 100 AND stock < 5 that the app evaluates.
Saved in this browser only. Part of Behavioral patterns (0/11).