DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Design Pattern: Interpreter

The Interpreter pattern is used to interpret or evaluate expressions in a simple language. It defines a grammar for expressions and a mechanism to interpret them. It is useful when you need to process or evaluate commands or rules repeatedly, like in calculators or scripting languages.

C# Code Example:

// Interface for expressions
public interface IExpression
{
    int Interpret();
}

// Expression for numbers
public class Number : IExpression
{
    private int _value;

    public Number(int value)
    {
        _value = value;
    }

    public int Interpret()
    {
        return _value;
    }
}

// Expression for addition
public class Addition : IExpression
{
    private IExpression _left;
    private IExpression _right;

    public Addition(IExpression left, IExpression right)
    {
        _left = left;
        _right = right;
    }

    public int Interpret()
    {
        return _left.Interpret() + _right.Interpret();
    }
}

// Expression for subtraction
public class Subtraction : IExpression
{
    private IExpression _left;
    private IExpression _right;

    public Subtraction(IExpression left, IExpression right)
    {
        _left = left;
        _right = right;
    }

    public int Interpret()
    {
        return _left.Interpret() - _right.Interpret();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create expressions: (10 + 5) - 3
        IExpression expression = new Subtraction(
            new Addition(new Number(10), new Number(5)),
            new Number(3)
        );

        // Interpret and display the result
        int result = expression.Interpret();
        Console.WriteLine($"Result of the expression: {result}"); // Output: Result of the expression: 12
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we have an IExpression interface that defines the Interpret method. The Number, Addition, and Subtraction classes implement this interface to represent different types of expressions. The code creates an expression that adds 10 and 5, then subtracts 3, and then interprets the result. The Interpreter pattern allows you to build and evaluate expressions flexibly.

Conclusion:

The Interpreter pattern is useful when you need to define a grammar and interpret expressions repeatedly. It is applied in situations like calculators, scripting language processors, or systems that need to evaluate rules or commands.

Source code: GitHub

Top comments (0)