Interpreter Pattern

Summary

  • The Interpreter pattern supports the interpretation of instructions written in a language or notation defined for a specific purpose. The notation is precise and can be defined in a form of grammar.
  • A common form of grammar is to make use of a set of terms. Terms are either defined as terminals (these are final terms) or as nonterminals (these comprise other terms).
  • The Interpreter Pattern matches supplied input (containing instructions and input data) against a predefined grammar to create an object structure. This process is referred to as parsing.
  • Once the object structure is created, these objects can be used to perform operations on the input and generate a resulting output. The operations are performed in the context of some input and output.
  • The Interpreter Pattern is not designed for large grammars, and can suffer performance problems with more complex grammars.

Class diagram: (see Interpreter Pattern code review)

Interpreter Pattern class diagram of sample code download

Usage

Use the Interpreter pattern when you have a grammar to be interpreted and:

  • The grammar can be translated into a set of classes.
  • The grammar is not too large.
  • Efficiency is not critical.