Interpreter pattern



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 {
        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;
        public void 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);

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


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 if __name__ == ‘__main__’: #Create applications and objects app […]