In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language.The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.[1] See also Composite pattern.
The Interpreter[2] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
Source:[3]
When a problem occurs very often, it could be considered to represent it as a sentence in a simple language(Domain Specific Languages) so that an interpreter can solve the problemby interpreting the sentence.
For example, when many different or complex search expressions must be specified.Implementing (hard-wiring) them directly into a class is inflexiblebecause it commits the class to particular expressions and makes it impossible to specify new expressions or change existing ones independently from (without having to change) the class.
Expression
class hierarchy and implementing an interpret
operation.Expression
instances.interpret
on the AST.The expression objects are composed recursively into a composite/tree structure that is calledabstract syntax tree (see Composite pattern).
The Interpreter pattern doesn't describe howto build an abstract syntax tree. This canbe done either manually by a client or automatically by a parser.
See also the UML class and object diagram below.
In the above UML class diagram, the Client
class refers to the common AbstractExpression
interface for interpreting an expressioninterpret(context)
.
The TerminalExpression
class has no children and interprets an expression directly.
The NonTerminalExpression
class maintains a container of child expressions(expressions
) and forwards interpret requeststo these expressions
.
The object collaboration diagram shows the run-time interactions: The Client
object sends an interpret request to the abstract syntax tree.The request is forwarded to (performed on) all objects downwards the tree structure.
The NonTerminalExpression
objects (ntExpr1,ntExpr2
) forward the request to their child expressions.
The TerminalExpression
objects (tExpr1,tExpr2,…
) perform the interpretation directly.
This C++11 implementation is based on the pre C++98 sample code in the book.
class Context;
class BooleanExp ;
class VariableExp;
class Context ;
class VariableExp : public BooleanExp ;
class AndExp : public BooleanExp ;
int main
The program output is: