The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Interpreter Design Pattern

Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

The Interpreter design pattern solves problems like: How can a grammar for a simple language be defined so that sentences in the language can be interpreted?

Open in the interactive referenceDownload the PDF reference

Problem

The Interpreter design pattern solves problems like:
How can a grammar for a simple language be defined
so that sentences in the language can be interpreted?
See Applicability section for all problems Interpreter can solve. See Solution section for how Interpreter solves the problems.

  • "If a particular kind of problem occurs often enough, then it might be worthwhile to express instances of the problem as sentences in a simple language. Then you can build an interpreter that solves the problem by interpreting these sentences." [GoF, p243]
  • Specifying a search expression, for example, is a problem that often occurs. Implementing (hard-wiring) it each time it is needed directly within a class (Context) is inflexible because it commits (couples) the class to a particular expression and makes it impossible to change or reuse the expression later independently from (without having to change) the class.
  • That's the kind of approach to avoid if we want to specify and change search expressions dynamically at run-time.
  • For example, an object finder with arbitrary (dynamically changeable) search criteria.
    Instead of hard-wiring a search expression each time it is needed, it should be possible to define a simple query language so that search expressions can be speci­fied and interpreted (evaluated) dynamically (see Implementation and Sample Code / Example 2).

Solution

The Interpreter design pattern provides a solution:
(1) Define a grammar for a simple language by an Expression class hierarchy.
(2) Represent a sentence in the language by an AST (abstract syntax tree).
(3) Interpret a sentence by calling interpret(context) on an AST.
Describing the Interpreter design in more detail is the theme of the following sections. See Applicability section for all problems Interpreter can solve.

  • (1) Define a grammar for a simple language by an Expression class hierarchy:
    • Define an interface for interpreting an expression (AbstractExpression | interpret(context)).
    • Define classes (TerminalExpression) that implement the interpretation.
      "[…] many kinds of operations can "interpret" a sentence." [GoF, p254]
      Usually, an interpreter is considered to interpret (evaluate) an expression and return a simple result, but any kind of operation can be implemented.
    • Define classes (NonTerminalExpression) that forward interpretation to their child expressions.
  • (2) Represent a sentence in the language by an AST (abstract syntax tree):
    • Every sentence in the language is represented by an abstract syntax tree made up of TerminalExpression instances (tExpr1,tExpr2,…) and NonTerminalExpression instances (ntExpr1,ntExpr2,…).
    • The expression objects are composed recursively into a composite/tree structure that is called abstract syntax tree (see Composite pattern).
      Terminal expressions have no child expressions and perform interpretation directly.
      Nonterminal expressions forward interpretation to their child expressions.

      "The Interpreter pattern doesn't explain how to create an abstract syntax tree. In other words, it doesn't address parsing. The abstract syntax tree can be created by a […] parser, or directly by the client." [GoF, p247] [BGI]
  • (3) Interpret a sentence by calling interpret(context) on an AST.
    • See also Implementation and Sample Code.

Background Information

  • A Parser Generator
    uses a grammar file to generate a parser. The parser can be updated simply by updating the grammar and regenerating. The generated parser can use efficient techniques to create ASTs that would be hard to build and maintain by hand.
  • ANTLR (ANother Tool for Language Recognition) [TP07]
    is a open source parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frame­works. From a grammar, ANTLR generates a parser that can build and walk parse trees.

Applicability

Design Problems

  • Interpreting Sentences in Simple Languages
    (Domain Specific Languages)
    • How can a grammar for a simple language be defined
      so that sentences in the language can be interpreted?
    • How can instances of a problem be represented as sentences in a simple language
      so that these sentences can be interpreted to solve the problem?

Not included on this page: Intent, Motivation, Structure, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.