Interpreter is a behavioral pattern that provides a way to evaluate language grammar or expression. This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc.
In the example below an interface Expression is created along with concrete classes implementing Expression interface – TerminalExpression, OrExpression, AndExpression. InterpreterPatternDemo will use Expression interface to create rules and demonstrate parsing of expressions.
Step 1 : Create an expression interface
public interface Expression {
boolean interpret(String context);
}
Step 2 : Create concrete classes implementing the above interface
public class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data) {
this.data = data;
}
@Override
public boolean interpret(String context) {
return context.contains(data);
}
}
public class OrExpression implements Expression {
private Expression exp1;
private Expression exp2;
public OrExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public boolean interpret(String context) {
return exp1.interpret(context) || exp2.interpret(context);
}
}
public class AndExpression implements Expression {
private Expression exp1;
private Expression exp2;
public AndExpression(Expression exp1, Expression exp2) {
this.exp1 = exp1;
this.exp2 = exp2;
}
@Override
public boolean interpret(String context) {
return exp1.interpret(context) && exp2.interpret(context);
}
}
Step 3 : InterpreterPatternDemo uses Expression class to create rules and then parse them
public class InterpreterPatternDemo {
public static Expression getMaleExpression() {
Expression robert = new TerminalExpression("Robert");
Expression john = new TerminalExpression("John");
return new OrExpression(robert, john);
}
public static Expression getMarriedWomanExpression() {
Expression julie = new TerminalExpression("Julie");
Expression married = new TerminalExpression("Married");
return new AndExpression(julie, married);
}
public static void main(String[] args) {
Expression isMale = getMaleExpression();
Expression isMarriedWoman = getMarriedWomanExpression();
System.out.println("John is male? " + isMale.interpret("John"));
System.out.println("Julie is a married woman? " + isMarriedWoman.interpret("Married Julie"));
}
}
The output will be :
John is male? true
Julie is a married woman? true