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

Implementation of PHP Facades

Example <?php class RealRoute{ public function get(){ Echo’Get me’; } } class Facade{ public static $resolvedInstance; public static $app; public static function __callStatic($method,$args){ $instance = static::getFacadeRoot(); if(!$instance){ throw new RuntimeException(‘A facade root has not been set.’); } return $instance->$method(…$args); } // Get the Facade root object public static function getFacadeRoot() { return static::resolveFacadeInstance(static::getFacadeAccessor()); } protected […]