Behavioral Design Pattern
Interpreter Design Pattern in Java
Represent and evaluate simple language rules using an object-based grammar.
In this lesson: Interpreter models a small grammar as classes. Each expression evaluates itself against a context.
Overview
interface Expression { boolean interpret(String value); } final class Equals implements Expression { private final String expected; Equals(String expected) { this.expected = expected; } public boolean interpret(String value) { return expected.equals(value); } }
Implementation
Expression rule = new Equals("JAVA");
System.out.println(rule.interpret("JAVA"));
Use Interpreter for small rule languages, search filters, configuration expressions, and domain-specific commands. For large grammars, a parser library is usually better.
When should you use it?
Use Interpreter for small, stable grammars such as search filters, configuration expressions, and domain-specific rules. Choose a parser library for complex languages.
Next step: Continue with the Design Patterns course and explore the next pattern.