The Interpreter Design Pattern is a behavioral design pattern that defines a grammar for a language and provides an interpreter to interpret sentences in that language. It is used to evaluate and interpret expressions or scripts. This pattern is useful when you have a language to interpret, and you want to implement a way to parse and execute it.
Here’s a C# example of the Interpreter Design Pattern with a use case for interpreting arithmetic expressions:
Define the Abstract Expression
Define an abstract expression class that declares an Interpret
method. This method is used to interpret the expression.
public abstract class Expression
{
public abstract int Interpret();
}
Create Terminal and Non-terminal Expressions
Implement concrete expressions by extending the abstract expression. Terminal expressions represent individual values, and non-terminal expressions represent operations.
public class NumberExpression : Expression
{
private int number;
public NumberExpression(int number)
{
this.number = number;
}
public override int Interpret()
{
return number;
}
}
public class AddExpression : Expression
{
private Expression left;
private Expression right;
public AddExpression(Expression left, Expression right)
{
this.left = left;
this.right = right;
}
public override int Interpret()
{
return left.Interpret() + right.Interpret();
}
}
public class SubtractExpression : Expression
{
private Expression left;
private Expression right;
public SubtractExpression(Expression left, Expression right)
{
this.left = left;
this.right = right;
}
public override int Interpret()
{
return left.Interpret() - right.Interpret();
}
}
Create the Context Class
Create a context class that holds the expression and interprets it.
public class Context
{
private Expression expression;
public Context(Expression expression)
{
this.expression = expression;
}
public int Interpret()
{
return expression.Interpret();
}
}
Use Case – Interpreting Arithmetic Expressions
Use the Interpreter Design Pattern to interpret and evaluate arithmetic expressions
class Program
{
static void Main(string[] args)
{
// Represent the expression: (10 + 5) - (7 + 3)
Expression expression = new SubtractExpression(
new AddExpression(new NumberExpression(10), new NumberExpression(5)),
new AddExpression(new NumberExpression(7), new NumberExpression(3))
);
Context context = new Context(expression);
int result = context.Interpret();
Console.WriteLine("Result: " + result);
}
}
In this example, the Interpreter Design Pattern allows you to interpret and evaluate arithmetic expressions by creating an expression tree. The Context
class holds the root of the expression tree, and by invoking Interpret
, it evaluates the entire expression. This pattern is useful for creating custom languages or interpreting specific expressions or scripts.