This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Welcome to today’s learning, today we are going to learn a few scenarios, but very interesting mode —- interpreter mode. This month, I will talk about Java design patterns in detail. Please click on the profile picture and follow my column. I will keep updating.

Series of articles:

Singletons of design patterns

The factory model of design pattern

The builder pattern of design patterns

Proxy patterns of design patterns

The visitor pattern of design patterns

Adaptor patterns for design patterns

The designer mode of the design mode

Java state pattern | monitoring state change anytime and anywhere

Java observer pattern | how to notice things change

Java mode | how to record history information memorandum

Java iterator pattern model | how to access each element

Java the flyweight pattern | how to share the object

. Under continuous update

Without further ado, let’s get to the point

Interpreter mode

The Interpreter Pattern, which provides a way to evaluate a language’s syntax or expressions, is a behavior-based Pattern. This pattern implements an expression interface that interprets a particular context.

We often encounter around, such as rules engine, regular expressions, SQL parsing and so on. We need to understand how the interpreter works. Think about how complex logic can be represented by more concise rules.

This is officially defined as: to define a representation of the grammar rules of the language and to provide an interpreter to handle the syntax in a sentence.

  • What I understand is to customize some rules and deal with the logic accordingly. I’m going to explain this rule, and the process of processing the logic is the content of the explanation.

  • In programming languages, if-else is used as the syntax for conditions, and for is used as the syntax identifier for loops. For another example, “I love to dig gold” is a Chinese sentence. We can use nouns, verbs, adjectives and other grammatical rules to intuitively describe the sentence.

Let’s look at the picture

  • Context: Contains global information about the interpreter.

  • AbstractExpression: defines the operations of an interpreter, which can be abstract classes or interfaces, and states that any inherited or implemented child node needs to implement these operations.

  • TerminalExpression: used to interpret all terminal expressions: (e.g. parse c=a+b, a and b are terminals, and the interpreter that parses a and b is a TerminalExpression)

  • NonterminalExpression: Interprets all non-terminalexpressions: (e.g. c=a+b, “+” is a non-terminalexpression, and the interpreter parsing” +” is a non-terminalexpression)

Let’s dig deeper with actual code:

The code shown

Let’s create an example of a logical and interpreter. In simple terms, the expression is determined by the string name to determine whether the expression exists at the same time. If the expression exists, it is printed true, and if one or none exists, it is printed false. In the following code, we create an interface Expression and a concrete class that implements the Expression interface, define a TerminalExpression class as the main interpreter, and define a non-terminal Expression class. Here OrExpression and AndExpression are non-terminal expressions that deal with different logic respectively.

// Define an expression
public interface Expression {

    // The string name is used to determine whether the expression exists at the same time. If it exists, print true; if it exists, print false.
    boolean interpreter(String con);
}


// The terminal expression class
public class TerminalExpression implements Expression{
    String data;
    public TerminalExpression(String data) {
        this.data = data;
    }
    @Override
    public boolean interpreter(String con) {
        if(con.contains(data)) {
            return true;
        } else {
            return false; }}}// Non-terminal expression class (and)
public class AndExpression implements Expression {
    Expression expr1;
    Expression expr2;
    public AndExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }
    public boolean interpreter(String con) {
        returnexpr1.interpreter(con) && expr2.interpreter(con); }}// Non-terminal expression class (or)
public class OrExpression implements Expression {
    Expression expr1;
    Expression expr2;
    public OrExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }
    public boolean interpreter(String con) {
        returnexpr1.interpreter(con) || expr2.interpreter(con); }}/ / call
public class Client {
    public static void main(String[] args) {
        Expression person1 = new TerminalExpression("mick");
        Expression person2 = new TerminalExpression("mia");
        Expression isSingle = new OrExpression(person1, person2);
        Expression spike = new TerminalExpression("spike");
        Expression mock = new TerminalExpression("mock");
        Expression isCommitted = new AndExpression(spike, mock);
        System.out.println(isSingle.interpreter("mick"));
        System.out.println(isSingle.interpreter("mia"));
        System.out.println(isSingle.interpreter("max"));
        System.out.println(isCommitted.interpreter("mock, spike"));
        System.out.println(isCommitted.interpreter("Single, mock")); }}/ / output
true
true
false
true
false
Copy the code

From the above code, we can see that words within the expression range will return true, and words not within the expression range will return false.

That is, the expression interpreter’s parsing logic is placed in different expression expression nodes so that context can be resolved by adding different nodes.

Point: Therefore, the essence of the interpreter pattern principle is to equip the syntax with an interpreter, through which more detailed operations can be performed.

So much for OK code, the interpreter pattern is rarely used, mainly in SQL parsing, symbolic processing engine scenarios, and so on. So you just have to understand. Spring spel expression you can see!

conclusion

I think this pattern is easy to extend. No other advantages have been found yet

Usage Scenario analysis:

  • When a language needs to be interpreted and executed. Such as the different meanings of nodes indicated by <> parentheses in XML documents.

  • When the problem is repeated and can be expressed in a simple language. For example, if-else statements are used to make conditional statements. When a block of if-else statements appears in code, they are interpreted as conditional statements without having to be redefined and interpreted every time

overtones

Thank you for reading, and if you feel you’ve learned something, please like it and follow it.

I have included this chapter in my project, click on the project below, and follow the column. I will publish dry items every day, and I will continue to enter design patterns this month.

Come on! See you next time!