Interpreter Pattern The interpreter design pattern enables the reading and interpreting of instruction that are written in a specific purpose language or notation. The interpreter uses the representation of the grammar of the language in order to interpret the language instructions. Using the pattern can cause a performance issue. Use Cases for the Interpreter PatternYou should use the pattern in the following cases:

You have a grammar for a language that isn’t large and complicated.

Performance isn’t an issue in the application.

You have a way to parse the grammar in an efficient way.

UML Diagram

Example in C# The following code is an example of how to implement the pattern:

#region Context

publicclassInterpreterContext

{

}

#endregion

#region Expression

publicabstractclassAbstractTerm

{

#region Methods

publicabstractvoid Interpret(InterpreterContext context);

#endregion

}

#endregion

#region Concrete Expressions

publicclassTerminalTerm : AbstractTerm

{

#region Methods

publicoverridevoid Interpret(InterpreterContext context)

{

Console.WriteLine("Terminal");

}

#endregion

}

publicclassNonterminalTerm : AbstractTerm

{

#region Methods

publicoverridevoid Interpret(InterpreterContext context)

{

Console.WriteLine("Nonterminal");

}

#endregion

}

#endregion

The example is very simple and follows the instructions of the UML shown above.

The following code is an example scenario of how to run the pattern in console application:

InterpreterContext context = newInterpreterContext();

List<AbstractTerm> terms = newList<AbstractTerm>();

// Build the terms tree

terms.Add(newTerminalTerm());

terms.Add(newNonterminalTerm());

terms.Add(newTerminalTerm());

// Interpret the tree

foreach (AbstractTerm term in terms)

{

term.Interpret(context);

}

Console.Read();

Summary To sum up the post, I explained the interpreter design pattern in the post. The pattern is rarely used and implies performance issues in the application. I hope that you enjoyed the journey in the world of design patterns and that the posts where helpful. See you in the next posts in other development subjects.