Home / Design Pattern / Behavioral / Interpreter

Interpreter Design Pattern in Java

Interpreter defines a small language (grammar) and a way to read and calculate sentences of that language.

Real life example

A calculator understands 10 + 5 - 3 and gives the answer.

When to use

You have simple rules or expressions that repeat, like math formulas, search filters or rules.

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

public class Main {
    public static void main(String[] args) {
        Expr e = new Sub(new Add(new Num(10), new Num(5)), new Num(3));   // (10 + 5) - 3
        System.out.println(e.eval());                                     // 12
    }
}

interface Expr { int eval(); }

class Num implements Expr {
    private int n;
    Num(int n) { this.n = n; }
    public int eval() { return n; }
}
class Add implements Expr {
    private Expr left, right;
    Add(Expr l, Expr r) { left = l; right = r; }
    public int eval() { return left.eval() + right.eval(); }
}
class Sub implements Expr {
    private Expr left, right;
    Sub(Expr l, Expr r) { left = l; right = r; }
    public int eval() { return left.eval() - right.eval(); }
}

Output

12