Monday, January 28, 2008

* Patterns : Interpreter Behavioral Pattern

Interpreter Behavioral Pattern as name suggests is used to interpret sentences in langauge provided represented in a particular form.

The langauge should be representable in form of abstract syntax tree. Two types of nodes are used for expressions : Terminal Expressions & Non-Terminal Expressions.

Let's take an example of a command line calculator which can take expressoins in form of a+b-c+d and return the output.

The class diagram representing such calculator can be following :

Interpreter

Calculator class is an example of an Interpreter which parses the input statement and creates tree using NumberExpression (Terminal) & OperatorExpression (Non-Terminal). Both Expression classes have an abstract base which is used by Calculator to evaluate the tree.

public class Calculator
{
    BaseExpression bTree; //not used.
    Context ctx;
    public void Calculate(string expr)
    {
        //expr = "5+1-3";
        ctx = new Context();
        List<BaseExpression> tree = new List<BaseExpression>();
        char[] elements = expr.ToCharArray();
        foreach (char c in elements)
        {
            if (c.ToString().Equals("+") || c.ToString().Equals("-"))
            {
                tree.Add(new OperatorExpression(c));
            }
            else
            {
                tree.Add(new NumberExpression((int)c-48));
            }
        }
        foreach (BaseExpression exp in tree)
        {
            exp.Evaluate(ctx);
        }
        Console.WriteLine(ctx.Total);
    }
}

Download Interpreter Behavioral Pattern Source code

Other Design Patterns

2 comments: