Behavioral Design Pattern · Java

Interpreter Design Pattern in Java

Represent a small language and interpret its expressions.

What is Interpreter?

Interpreter is useful when users provide simple rules or queries. Each grammar element becomes an expression that can evaluate a context.

Beginner-friendly Java example

Focus on the roles in the example first. The pattern becomes easier when you can identify the sender, receiver, context, state, or strategy involved.

interface Expression {
    boolean interpret(String input);
}

class ContainsExpression implements Expression {
    private final String word;

    ContainsExpression(String word) {
        this.word = word;
    }

    public boolean interpret(String input) {
        return input.contains(word);
    }
}

Expression rule = new ContainsExpression("urgent");
boolean matches = rule.interpret("urgent request");

Benefits and trade-offs

Benefits
  • Keeps responsibilities focused.
  • Reduces conditional and tightly coupled code.
  • Makes behavior easier to extend and test.
Trade-offs
  • Can introduce extra objects and interfaces.
  • Too many small classes can make simple logic harder to follow.

Real-time use cases

  • Search filters
  • Feature rules
  • Simple command languages
  • Permission expressions
Key takeawayRepresent a small language and interpret its expressions. Use it when behavior or communication is changing faster than the objects themselves.