7.14. Interpreter
EN: Interpreter
PL: Interpreter
Type: class
The Interpreter design pattern is a behavioral design pattern that specifies how to evaluate sentences in a language. This pattern is used to interpret sentences in a language and represents a grammar as a hierarchy of composite objects.
In Python, we can implement the Interpreter pattern using classes. Here's a simple example:
First, we define an AbstractExpression
class that declares an abstract
interpret
method:
class AbstractExpression:
def interpret(self):
pass
Then, we define a TerminalExpression
class that implements the interpret
method:
class TerminalExpression(AbstractExpression):
def interpret(self):
print("Terminal expression is being interpreted.")
Finally, we can use the AbstractExpression
and TerminalExpression
classes
like this:
class NonterminalExpression(AbstractExpression):
def __init__(self, expression):
self._expression = expression
def interpret(self):
print("Nonterminal expression is being interpreted.")
self._expression.interpret()
terminal_expression = TerminalExpression()
nonterminal_expression = NonterminalExpression(terminal_expression)
nonterminal_expression.interpret()
Nonterminal expression is being interpreted.
Terminal expression is being interpreted.
In this example, the NonterminalExpression
interprets a TerminalExpression
.
7.14.1. Pattern
7.14.2. Problem
7.14.3. Solution