Interpreter
Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Last updated
Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Last updated
Interpreter is a design pattern that belongs to the Behavioral Pattern group.
The Interpreter Pattern helps programmers "build" "dynamic" objects by reading a description of the object and then "building" the object according to that description.
For example, write a program that allows users to enter the command line according to a pre-specified structure. The program will recognize the Command based on its structure and return appropriate results.
Components in the model:
AbstractionExpression: Declare an interface for performing an operation.
TerminalExpression: Implements an interpretation operation associated with terminal symbols, acting as a required expression for all terminal symbols in a sentence.
NonterminalExpression: Can contain an internal TerminalExpression and can also contain another NonterminalExpression. It serves as the “grammar” of the specification language.
Context : Is the information object to perform interpretation. This object is global to the interpretation process (shared between nodes).
Advantage
Reduce dependency between abstraction and implementation (loose coupling).
Reduce the number of unnecessary subclasses.
The code will be cleaner and the application size will be smaller.
Easier to maintain.
Easy to expand later.
Allows you to hide implementation details from the client.
Disadvantage
The constructed specification language requires a simple grammatical structure.
Performance is not guaranteed
Use Interpreter Pattern when we want:
Simple grammar set. This pattern needs to define at least one class for each rule in the grammar. Therefore grammars containing many rules can be difficult to manage and maintain.
Don't care much about performance. Because the grammar is analyzed in a hierarchical structure (tree), performance is not guaranteed.
The Interpreter Pattern is often used in compilers, defining grammars, rules, SQL, XML parsers, etc.
The abstract syntax tree is an implementation of the Composite pattern .
Interpreters often use an Iterator to traverse the structure.
Visitor can be used to maintain behavior on each node in the class's abstract syntax tree.