In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, the interpreter pattern is a
design pattern
A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
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 In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "comp ...
and is used to evaluate (interpret) the sentence for a client.
See also
Composite pattern In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "comp ...
.
Overview
The Interpreter
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.
What problems can the Interpreter design pattern solve?
* A
grammar
In linguistics, the grammar of a natural language is its set of structure, structural constraints on speakers' or writers' composition of clause (linguistics), clauses, phrases, and words. The term can also refer to the study of such constraint ...
for a simple language should be defined
* so that sentences in the language can be interpreted.
When a problem occurs very often, it could be considered to represent it as a sentence in a simple language
(
Domain Specific Languages
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. There are a wide variety of DSLs, ranging ...
) so that an interpreter can solve the problem
by interpreting the sentence.
For example, when many different or complex search expressions must be specified.
Implementing (hard-wiring) them directly into a class is inflexible
because 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.
What solution does the Interpreter design pattern describe?
* Define a grammar for a simple language by defining an
Expression
class hierarchy and implementing an
interpret()
operation.
* Represent a sentence in the language by an abstract syntax tree (AST) made up of
Expression
instances.
* Interpret a sentence by calling
interpret()
on the AST.
The expression objects are composed recursively into a composite/tree structure that is called
''abstract syntax tree'' (see
Composite pattern In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "comp ...
).
The Interpreter pattern doesn't describe how
to build an abstract syntax tree. This can
be done either manually by a client or automatically by a
parser.
See also the UML class and object diagram below.
Uses
* Specialized database query languages such as
SQL.
* Specialized computer languages that are often used to describe communication protocols.
* Most general-purpose computer languages actually incorporate several specialized languages.
Structure
UML class and object diagram

In the above
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally ...
class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the r ...
, the
Client
class refers to the common
AbstractExpression
interface for interpreting an expression
interpret(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 requests
to 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.
UML class diagram
Examples
BNF
The following
Backus–Naur form example illustrates the interpreter pattern. The grammar
expression ::= plus , minus , variable , number
plus ::= expression expression '+'
minus ::= expression expression '-'
variable ::= 'a' , 'b' , 'c' , ... , 'z'
digit = '0' , '1' , ... , '9'
number ::= digit , digit number
defines a language that contains
Reverse Polish Notation
Reverse Polish notation (RPN), also known as reverse Łukasiewicz notation, Polish postfix notation or simply postfix notation, is a mathematical notation in which operators ''follow'' their operands, in contrast to Polish notation (PN), in whi ...
expressions like:
a b +
a b c + -
a b + c a - -
C#
This structural code demonstrates the Interpreter patterns, which using a defined grammar, provides the interpreter that processes parsed statements.
using System;
using System.Collections.Generic;
namespace OOP;
class Program
class Context
interface IExpression
abstract class OperatorExpression : IExpression
class EqualsExpression : OperatorExpression
class OrExpression : OperatorExpression
class MyExpression : IExpression
Java
public class Interpreter
While the interpreter pattern does not address parsing,
[ a parser is provided for completeness.
private static Expr parseToken(String token, ArrayDeque stack)
public static Expr parse(String expression)
Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.
public static void main(final String[] args)
}
]
PHP (Example 1)
/**
* AbstractExpression
*/
interface Expression
/**
* TerminalExpression
*/
class TerminalExpression implements Expression
/**
* NonTerminalExpression
*/
abstract class NonTerminalExpression implements Expression
/**
* NonTerminalExpression - PlusExpression
*/
class PlusExpression extends NonTerminalExpression
/**
* NonTerminalExpression - MinusExpression
*/
class MinusExpression extends NonTerminalExpression
/**
* Client
*/
class InterpreterClient
// test.php
function loadClass($className)
spl_autoload_register('loadClass');
(new InterpreterClient())->main();
//result: -16
PHP (Example 2)
Based on the example above with another realization of the client.
/**
* Client
*/
class InterpreterClient
JavaScript
As JavaScript is dynamically typed, we do not implement an interface.
// Nonterminal expression
class Plus
// Nonterminal expression
class Minus
// Nonterminal expression
class Times
// Nonterminal expression
class Divide
// Terminal expression
class Number
// Terminal expression
class Variable
// Client
class Parse
var res = new Parse().parse("16 v * 76 22 - -");
console.log(res)
//666
See also
* Backus–Naur form
* Combinatory logic in computing
* '' Design Patterns''
* Domain-specific language
* Interpreter (computing)
In computer science, an interpreter is a computer program that directly execution (computers), executes instructions written in a Programming language, programming or scripting language, without requiring them previously to have been Compiler, co ...
References
External links
Interpreter implementation
in Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
Interpreter implementation
in C++
SourceMaking tutorial
Interpreter pattern description from the Portland Pattern Repository
{{Design Patterns Patterns
Articles with example C Sharp code
Articles with example Java code
Software design patterns