Detailed explanation of interpreter mode of Java design mode

The beginning of Dr. Yan Hong's Book Java and patterns describes the Interpreter pattern as follows:

The Interpreter pattern is the behavior pattern of a class. Given a language, the Interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. The client can use this interpreter to interpret sentences in this language.

Structure of Interpreter pattern

Next, take a schematic system as an example to discuss the structure of the Interpreter pattern. The structure diagram of the system is as follows:

The roles involved in the pattern are as follows:

(1) abstract expression role: declare an abstract interface that all concrete expression roles need to implement. This interface is mainly an interpret () method, which is called interpretation operation.

(2) terminal expression role: it implements the interface required by the abstract expression role, mainly an interpret () method; Each terminator in grammar has a specific terminator expression corresponding to it. For example, there is a simple formula r = R1 + R2, in which R1 and R2 are terminators, and the corresponding interpreter that parses R1 and R2 is terminator expression.

(3) non terminal expression role: every rule in grammar requires a specific non terminal expression. Non terminal expression is generally an operator or other keyword in grammar. For example, in formula r = R1 + R2, "+" is a non terminal, and the interpreter that parses "+" is a non terminal expression.

(4) context role: the task of this role is generally used to store the specific values corresponding to each terminator in the grammar, such as R = R1 + R2. We assign 100 to R1 and 200 to R2. This information needs to be stored in the environment role. In many cases, it is enough for us to use map to act as the environment role.

In order to illustrate the implementation of the Interpreter pattern, the simplest grammar and the implementation of the corresponding Interpreter pattern are given here, which is to simulate the operation and evaluation of Boolean expressions in Java language.

In this language, terminators are Boolean variables, that is, constants true and false. Non terminator expressions contain Boolean expressions such as operators and, or, and not. This simple grammar is as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>