The Interpreter Design Pattern defines the grammatical representation for an object-oriented programming language. It governs the nuances of syntax and provides users with a concrete interpreter that will refer to the representation provided by the pattern itself to decode lines of code written in that particular language. A simple way to think of it will be to imagine the work of an interpreter. What an interpreter does is convert sentences said or written in a foreign language according to a set of rules, to a language that is easily understandable by you. The pattern works as the set of rules here and the interpreter follows is.
Table of Contents
Definition
As defined by the Gang of Four book of design patterns, ‘given a particular language, the interpreter pattern defines a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.’
Structure
- AbstractExpression(): This is the main interface where the operation is performed.
- Terminal Expression(): Interprets for terminal expressions
- Nonterminal Expression(): Interprets for non-terminal expressions
- Context(String): The String that needs to be interpreted
- Client(): Responsible for building or passing the Abstract Syntax Tree (ABS)
Example and Code
The following is a simple example of a language representation. If the word being used is ‘OR’ either of the two expressions will be returned. If the word being used is ‘AND’, both the expressions will be returned.
public class interface Test { Boolean interpret(String word); } // This class will implement the word. It is kept as a check to make sure the word in context is the same as what the interpreter is using. class TerminalExpression implements Test { String word; public TerminalExpression (String word) this.word = word; public Boolean interpret(String wrd) { if (wrd.equals(“word”)) return true; else return false; } } //Now let us set the words for the interpreter by making two separate classes for OR and AND. class wordOR implements Test { Test wrd1; Test wrd2; public ORword(Test wrd1, Test wrd2) { this.wrd1 = wrd1; this.wrd2 = wrd2; } public boolean interpret(String wrd) return wrd1.interpret(wrd) || wrd2.interpret(wrd); } } class wordAND implements Test { Test wrd1; Test wrd2; public ANDword(Test wrd1, Test wrd2) { this.wrd1 = wrd1; this.wrd2 = wrd2; } public boolean interpret(String wrd) return wrd1.interpret(wrd) && wrd2.interpret(wrd); } }
When to use the Interpreter Design Pattern?
The Interpreter Design Pattern finds prominence when you want to generate an Abstract Syntax Tree by referring to a simple set of grammar at your disposal. Another example where Interpreter patterns are extensively used are in report generator applications. As each output needs to be unique from the one before, the interpreter is better equipped to read such situations as compared to other design patterns.
0 Comments