DEV Community

eidher
eidher

Posted on • Edited on

Interpreter Pattern

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

Alt Text

Participants

  • AbstractExpression: declares an interface for executing an operation
  • TerminalExpression: implements an Interpret operation associated with terminal symbols in the grammar. An instance is required for every terminal symbol in the sentence.
  • NonterminalExpression: one such class is required for every rule R ::= R1R2...Rn in the grammar. Maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn. Implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
  • Context: contains information that is global to the interpreter
  • Client: builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes. Invokes the Interpret operation

Code

public class Main {

    public static void main(String[] args) {
        Context context = new Context();
        List<AbstractExpression> list = new ArrayList<>();
        list.add(new TerminalExpression());
        list.add(new NonterminalExpression());
        list.add(new TerminalExpression());
        list.add(new TerminalExpression());

        for (AbstractExpression exp : list) {
            exp.interpret(context);
        }

    }
}

public class Context {
}

public interface AbstractExpression {
    void interpret(Context context);
}

public class TerminalExpression implements AbstractExpression {

    @Override
    public void interpret(Context context) {
        System.out.println("Called Terminal.interpret()");
    }
}

public class NonterminalExpression implements AbstractExpression {

    @Override
    public void interpret(Context context) {
        System.out.println("Called Nonterminal.interpret()");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Called Terminal.interpret()
Called Nonterminal.interpret()
Called Terminal.interpret()
Called Terminal.interpret()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)