Interpreter Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Frequency of use:   low

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • AbstractExpression  (Expression)
    • declares an interface for executing an operation
  • TerminalExpression  ( ThousandExpression, HundredExpression, TenExpression, OneExpression )
    • implements an Interpret operation associated with terminal symbols in the grammar.
    • an instance is required for every terminal symbol in the sentence.
  • NonterminalExpression  ( not used )
    • one such class is required for every rule R ::= R1R2...Rn in the grammar
    • maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.
    • implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
  • Context  (Context)
    • contains information that is global to the interpreter
  • Client  (InterpreterApp)
    • builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes
    • invokes the Interpret operation

sample code in C#

This structural code demonstrates the Interpreter patterns, which using a defined grammer, provides the interpreter that processes parsed statements.

Show code

// Interpreter pattern -- Structural example




This real-world code demonstrates the Interpreter pattern which is used to convert a Roman numeral to a decimal.

Show code

// Interpreter pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Interpreter pattern -- .NET optimized




Need to know more?

    see what others are saying about the Interpreter pattern





  • Better Code
  • Better Career
  • Better Lifestyle


Design Pattern
FrameworkTM 3.5


 
C# and VB.NET


     Here's what you get:
  • Gang of Four Patterns
  • Head First Patterns
  • Enterprise Patterns
  • SOA Patterns

  • WPF Best Practices
  • WCF Best Practices
  • LINQ Best Practices

  • Model View Controller
  • Model View Presenter
  • Model View ViewModel

  • More...

Click here for details

-- Instant Access --
Instant Download