Interpreter Design Pattern in Visual Basic .NET


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

This is about creating interpreter for a language which can be new language or existing one. To use the Interpreter Design Pattern effectively one should have good knowledge about computer language grammar.

We will see the UML diagram for the Interpreter Design Pattern


Classes and objects you find in Interpreter Design Pattern
Global information of the Interpreter is kept here

  • Client defines the object tree which represent the language with grammar. Syntax tree is built using instances of the NonterminalExpression and TerminalExpression classes
  • Invokes the Interpret operation.

Defines Interpret method used by Terminal and NonTerminal expressions
Implements an Interpret operation
Implements an Interpret operation

Interpreter Design Pattern Example in VB.NET

In this tutorial I will implement the Reverse Polish Notation (RPN) or Postfix notation. It is a mathematical notation in which operators follow their operands
Postfix expression can be written as 1 2 4 + – which is equivalent to (1+2-4)

First we will draw the UML diagram for our program

This is the algorithm for evaluating the postfix expression using stack

for each token in the postfix expression:
if token is an operator:
operand_1 ← pop from the stack
operand_2 ← pop from the stack
result ← evaluate token with operand_1 and operand_2
push result back onto the stack
else if token is an operand:
push token onto the stack
result ← pop from the stack

IExpression Interface

Add NonTerminal Expression Class

Substract NonTerminal Expression Class

Multiply NonTerminal Expression Class

Number Terminal Class

This is the client part of the above patter. We can use client to run the program

Finally you will see the following output