Skip to content
On this page

Interpreter

Given a language, define a representation of its grammar along with an interpreter that uses this representation to interpret sentences in the language.

The Interpreter pattern is a solution designed for specific problems. For example, when matching strings, the matching conditions are very flexible, making it inflexible to implement directly through code. Let's take an example with the following matching conditions:

  • Area codes and phone numbers represented by numbers starting with +, such as +861012345678.
  • Domain names starting with English letters, followed by English letters and numbers, separated by dots, such as www.liaoxuefeng.com.
  • File paths starting with /, such as /path/to/file.txt.
  • ...

Therefore, a general representation method—regular expressions—is needed for matching. A regular expression is just a string, but parsing the regular expression into a syntax tree and then matching a specific string requires an interpreter.

Implementing a complete interpreter for regular expressions is very complex, but using the Interpreter pattern is quite simple:

java
String s = "+861012345678";
System.out.println(s.matches("^\\+\\d+$"));

Similarly, when using JDBC, the SQL statements executed are strings, but ultimately, the SQL interpreter on the database server translates these SQL strings into executable code. This execution engine is also very complex, but for the user, it is sufficient to write the SQL string.

Implementing the Interpreter Pattern

Using the Interpreter pattern can simplify the design by abstracting the grammar and providing an interpreter to process sentences in that language.

Exercise

Implement a simple interpreter that outputs strings in SLF4J's log format:

java
log("[{}] start {} at {}...", LocalTime.now().withNano(0), "engine", LocalDate.now());
// [11:02:18] start engine at 2020-02-21...

Summary

  • The Interpreter pattern implements the interpretation and execution of user input through an abstract syntax tree.
  • The implementation of the Interpreter pattern is usually very complex and typically only solves a specific class of problems.
Interpreter has loaded