Table of Contents
Introduction to Interpreter Design pattern
Interpreter design pattern is a behavioral design pattern that is useful for designing systems where you need to interpret or evaluate structured data, scripts, or languages, such as configuration files, mathematical expressions, and even simple programming languages.
5 Real-World Applications
- Configuration Languages: Parsing and interpreting configuration files.
- Mathematical Expressions: Evaluating arithmetic expressions or formulas.
- Query Languages: Implementing query interpreters for databases or search engines.
- Scripting Engines: Creating interpreters for scripting languages within applications.
- Communication Protocols: Interpreting commands or data packets in communication protocols.
Sample code for Interpreter Design Pattern
1. Abstract Expression
Defines an interface for interpreting expressions. This interface typically includes an interpret
method that each concrete expression must implement.
public interface Expression {
int interpret();
}
2. Terminal Expression
Implements the interpret
method for terminal symbols in the grammar. These expressions represent the simplest elements in the language, such as numbers or variables.
public class Number implements Expression{
private int number;
public Number(int number) {
this.number = number;
}
@Override
public int interpret() {
return number;
}
}
3. Nonterminal Expression
Implements the interpret
method for non-terminal symbols. These expressions are composed of terminal and other non-terminal expressions, representing more complex structures or rules in the language.
public class Add implements Expression{
private Expression leftExpression;
private Expression rightExpression;
public Add(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret()+ rightExpression.interpret();
}
}
public class Subtract implements Expression{
private Expression leftExpression;
private Expression rightExpression;
public Subtract(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret() {
return leftExpression.interpret()- rightExpression.interpret();
}
}
Client Code
public class Main {
public static void main(String[] args) {
Expression five = new Number(5);
Expression four = new Number(4);
Expression three = new Number(3);
Expression addExpression = new Add(five, four);
Expression subtractExpression = new Subtract(addExpression, three);
int result = subtractExpression.interpret();
System.out.println("Result: "+ result);
}
}