Interpreter Pattern provides a way to evaluate the syntax or expression of a language, which is a behavioral pattern. This pattern implements an expression interface that interprets a particular context. This mode is used in SQL parsing, symbol processing engines, and more.
Intent: Given a language, define its grammar representation, and define an interpreter that uses this identifier to interpret sentences in the language.
Main solution: Construct an interpreter for interpreting sentences for some fixed grammars.
When to use: If a particular type of problem occurs frequently enough, it may be worthwhile to express each instance of the problem as a sentence in a simple language. This allows you to build an interpreter that solves the problem by interpreting the sentences.
How to solve: Component syntax tree, defining terminators and non-terminals.
Key Code: The component environment class, which contains some global information beyond the interpreter, typically a HashMap.
Application examples: Compiler, operation expression calculation.
Advantages: 1. The scalability is better and flexible. 2. Added a new way of interpreting expressions. 3. Easy to implement simple grammar.
Disadvantages: 1, the available scenes are relatively small. 2. It is difficult to maintain complex grammars. 3. The interpreter mode causes the class to swell. 4. The interpreter mode uses a recursive calling method.
Usage scenarios: 1. A sentence in a language that needs to be interpreted for execution can be represented as an abstract syntax tree. 2. Some recurring problems can be expressed in a simple language. 3. A scenario where a simple grammar needs to be explained.
Note: The available scenes are relatively small. If you encounter it in JAVA, you can use expression4J instead.
We will create an interface Expression and an entity class that implements the Expression interface. Define the TerminalExpression class as the primary interpreter in the context. The other classes OrExpression, AndExpression are used to create a combined expression.
InterpreterPatternDemo, our demo class uses the Expression class to create parsing of rules and presentation expressions.
Create an expression interface.
Create an entity class that implements the above interface.
InterpreterPatternDemo Use the Expression class to create rules and parse them.
Executing the program, outputting results:
John is male? true Julie is a married women? true