Interpreter pattern

Time:2019-8-13

Interpreter

I. Interpreter Model

1.1 Definition

  • Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language.

1.2 Roles

  • IExpression.
  • Terminal Expression.
  • Nonterminal Expression.
  • Context.

2. Realization

1.1 Create abstract interfaces

    public interface IExpression {
        void interpreter();
    }

1.2 Create Terminator Expressions

    public class TerminalExpression implements IExpression {
        @Override
        public void interpreter() {
            System.out.println("TerminalExpression interpreter ...");
        }
    }

1.3 Create non-terminal expressions

    public class NonterminalExpression implements IExpression {
        private TerminalExpression terminalExpressionA, terminalExpressionB;
        public NonterminalExpression(TerminalExpression terminalExpressionA, TerminalExpression terminalExpressionB){
            this.terminalExpressionA = terminalExpressionA;
            this.terminalExpressionB = terminalExpressionB;
        }
        @Override
        public void interpreter() {
            terminalExpressionA.interpreter();
            terminalExpressionB.interpreter();
            System.out.println("interpreter terminalExpressionA AND  terminalExpressionB ...");
        }
    }

1.4 Call

    public static void main(String[] args) {
        TerminalExpression expressionA = new TerminalExpression();
        TerminalExpression expressionB = new TerminalExpression();
        IExpression expression = new NonterminalExpression(expressionA, expressionB);
        expression.interpreter();
    }

1.5 Output

    TerminalExpression interpreter ...
    TerminalExpression interpreter ...
    interpreter terminalExpressionA AND  terminalExpressionB ...

Advantages and disadvantages

3.1 Advantages

  • Flexibility.
  • Expansibility is strong.

3.2 Disadvantages

  • Each grammar corresponds to an expression class, which overflows.
  • Complex grammar is difficult to implement.

IV. Source Code

    https://github.com/Seasons20/DisignPattern.git

END

Recommended Today

The method of obtaining the resolution of display by pyqt5

The code is as follows import sys from PyQt5.QtWidgets import QApplication, QWidget class Example(QWidget): def __init__(self): super().__init__() self.initUI() #Interface drawing to initui method def initUI(self): self.desktop = QApplication.desktop() #Get display resolution size self.screenRect = self.desktop.screenGeometry() self.height = self.screenRect.height() self.width = self.screenRect.width() print(self.height) print(self.width) #Show window self.show() if __name__ == ‘__main__’: #Create applications and objects app […]