Design Pattern | Interpreter Pattern
What Is the Interpreter Pattern?
- Interpreter means translator or interpreter.
- The Interpreter pattern interprets and represents the contents of a file written in a certain format by using a program that plays the role of an interpreter.
- In GoF design patterns, it is classified as a behavioral design pattern.
Interpreter Pattern Example Program
This example program parses a language written in a text file.
Class Diagram

The grammar of the language used as the parsing target is written in BNF notation.
<program> ::= program <command list>
<command list> ::= <command>* end
<command> ::= <repeat command> | <primitive command>
<repeat command> ::= repeat <number> <command list>
<primitive command> ::= go | right | left
<program>means that a sequence of commands follows the tokenprogram.<command list>means zero or more commands followed by the tokenend.<command>is either a repeat command or a primitive command.|means OR.<repeat command>represents repeated execution.<primitive command>represents a basic command such asgo,right, orleft.
The example separates grammar concepts into node classes such as program, command list, command, repeat command, and primitive command. Each node parses its own grammar rule and builds a syntax tree.
Advantages
When a language or rule set can be expressed as grammar, the Interpreter pattern lets each grammar rule be represented as a class. This makes parsing and extension easier, although it can become verbose if the grammar grows large.