Design Patterns

Interpreter



Design Pattern Type: Behavioral

GoF Statement of Intent:


Define a representation of the grammar for a language along with an interpreter that uses the representation to interpret sentences in the language.
Brief Overview:



Specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a computer language which knows how to interpret its symbol. The syntax tree of a sentence in the language is an instance of the Composite Design Pattern and is used to evaluate (interpret) the sentence.
UML Diagram:

Discussion and In-class Example:

This pattern is used to build an interpreter for a language. To use this pattern you must understand what a context free or formal grammar is. Simply put this is a set of rules that symbolically outline how valid "sentences" or "commands" are constructed in the language. Suppose you want to create a simple programming learning tool for children based on the Duck Pond Simulation example from the Strategy Design Pattern. Look at the simple program shown in the image below. The syntax for each of these statements is defined generically by this grammar.

The image below illustrates how the Interpreter organizes a set of classes to interpret its sentences. To interpret the language a call is made to the interpret() function in each expression object. Think of the argument context as a string or part of a string. Each, either parses a string to determine the components or it executes a root element.

Advantages of using the Interpreter
  1. Easy to implement the language because each grammar rule is represented by a class.
  2. Because of this the language is easy to change or extend.
  3. Most appropriate when the grammar is simple and simplicity is more important than efficiency.
  4. Frequently used for scripting and programming languages.
The main problem with using the Interpreter, however is that if the language has a large number of rules this can become too cumbersome and a parser/compiler design may be more appropriate.