What is the Interpreter Pattern?
The Interpreter Pattern provides a way to evaluate language grammar or expressions. It defines a representation for a grammar and an interpreter that uses the representation to interpret sentences in the language.
This pattern is especially useful when a particular type of problem occurs often enough to justify defining a simple language and interpreting it.
Interpreter Pattern Structure
The pattern typically involves:
- AbstractExpression: Declares an abstract interpret() method.
- TerminalExpression: Implements the interpret() method for symbols in the grammar.
- NonTerminalExpression: Implements the interpret() method for grammar rules that involve other expressions.
- Context: Contains information that's global to the interpreter and passed to expressions.
Python Implementation Example of Interpreter Pattern
Imagine you want to evaluate simple arithmetic expressions composed of numbers and addition/subtraction.
# Abstract Expression
class Expression:
def interpret(self):
pass
# Terminal Expression (for numbers)
class Number(Expression):
def __init__(self, value):
self.value = value
def interpret(self):
return self.value
# Non-Terminal Expression (for addition)
class Add(Expression):
def __init__(self, left, right):
self.left = left
self.right = right
def interpret(self):
return self.left.interpret() + self.right.interpret()
# Non-Terminal Expression (for subtraction)
class Subtract(Expression):
def __init__(self, left, right):
self.left = left
self.right = right
def interpret(self):
return self.left.interpret() - self.right.interpret()
# Client Code
expr = Subtract(
Add(Number(5), Number(3)), # 5 + 3
Number(2) # - 2
)
print("Result:", expr.interpret())
When to Use the Interpreter Pattern
Use the Interpreter Pattern when:
- You need to interpret sentences or expressions defined by a grammar.
- You want to model simple languages, commands, or rules using a class hierarchy.
- The grammar is simple and performance is not critical.
- You frequently encounter similar expressions that can be evaluated in a standard way.
Examples in Practice:
- Parsing and evaluating mathematical expressions
- Command scripting languages
- SQL expression parsing
- Regular expression engines