BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 2.0+

Interpreter Design Pattern

The interpreter pattern is a design pattern that is useful when developing domain-specific languages or notations. The pattern allows the grammar for such a notation to be represented in an object-oriented fashion that can easily be extended.

Testing the Interpreter

To test the interpreter and its parser we can evaluate some Polish notation strings from the Main method of the program. Add the following code to the Main method and execute the program to see the results. Try modifying the command strings to see the results. Remember that all values and operators should be separated with a single space.

Parser parser = new Parser();

string[] commands = new string[]
{
    "+ 5 6",
    "- 6 5",
    "+ - 4 5 6",
    "+ 4 - 5 6",
    "+ - + - - 2 3 4 + - -5 6 + -7 8 9 10"
};

foreach (string command in commands)
{
    ExpressionBase expression = parser.Parse(command);
    Console.WriteLine("{0} = {1}", expression, expression.Evaluate());
}

/* OUTPUT

(5 + 6) = 11
(6 - 5) = 1
((4 - 5) + 6) = 5
(4 + (5 - 6)) = 3
(((((2 - 3) - 4) + ((-5 - 6) + (-7 + 8))) - 9) + 10) = -14

*/
27 July 2009