Interpreter Pattern - TechNet Articles - United States (English) - TechNet Wiki

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. 

The interpreter pattern is a behavioral design pattern which specifies how to evaluate an expressions. There are two types of expressions :

Terminal : Which can be immediately evaluated.
Non-Terminal : Which can be decomposed into other Terminal or Non - Terminal expressions.

The terminal expressions represents the leaf nodes of the expression tree and the non-terminal nodes represents the compt-content">

Interpreter 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 reposites. The interpreter defines the behavior while the composite defines the structure. 

public class Context
{
    public string Name { get; set; }
 
    public Context(string name)
    {
        Name = name;
    }
}
 
public interface IExpression
{
    void Interpret(Context context);
}
  
  
public class TerminalExpression : IExpression
{
    public void Interpret(Context context)
    {
        Console.WriteLine("Terminal for {0}.", context.Name);
    }
}
 
 
public class NonterminalExpression : IExpression
{
    public IExpression Expression1 { get; set; }
 
    public IExpression Expression2 { get; set; }
 
    public void Interpret(Context context)
    {
        Console.WriteLine("Nonterminal for {0}.", context.Name);
        this.Expression1.Interpret(context);
        this.Expression2.Interpret(context);
    }
}

Here the context class represents the context of execution. The Terminal and NonTerminal expression classes represents a terminal where the Interpret method immediately process the expression while the Non-terminal calls the other expression in chain. 

To create the client code :

public static void BuildAndInterpretCommands()
    {
        var context = new Context("Abhishek");
        var root = new NonterminalExpression
                       ck" style="border:1px solid #7f9db9;overflow-y:auto;">
public static void BuildAndInterpretCommands()
    {
<{
                           Expression1 = new TerminalExpression(),
                           Expression2 = new TerminalExpression()
                       };
        root.Interpret(context);
    }

This code will print Abhishek in two terminal Expresisons while one non-terminal.