[Design Mode] - behavioral -11- interpreter mode

main character

  1. Abstract expression (Abstract Expression) Roles: interpreter defined interface conventions explaining the operation of the interpreter, comprising a main interpretation interpret ().
  2. Terminator expression (Terminal Expression) Roles: subclasses of the abstract expression is used to implement operations associated with terminal symbols in the grammar, the grammar each terminal symbol has a particular expression end corresponding thereto.
  3. Nonterminals expression (Nonterminal Expression) Roles: subclasses of the abstract expression is used to implement the grammar nonterminals operation, the grammar associated with each rule corresponds to a nonterminal expression.
  4. Environment (Context) Roles: typically comprises data or functions of the respective common interpreter required, generally used to transmit all shared data interpreter, the interpreter can obtain the latter values ​​here.
  5. Client (Client): The main task of the sentence or expression is to be analyzed into using the interpreter object description of the abstract syntax tree, and then call the interpretation interpreter, of course, you can also be accessed indirectly through the environmental role of interpreter of interpretation .

The sample code

//抽象表达式类
interface AbstractExpression
{
    public Object interpret(String info);    //解释方法
}
//终结符表达式类
class TerminalExpression implements AbstractExpression
{
    public Object interpret(String info)
    {
        //对终结符表达式的处理
    }
}
//非终结符表达式类
class NonterminalExpression implements AbstractExpression
{
    private AbstractExpression exp1;
    private AbstractExpression exp2;
    public Object interpret(String info)
    {
        //非对终结符表达式的处理
    }
}
//环境类
class Context
{
    private AbstractExpression exp;
    public Context()
    {
        //数据初始化
    }
    public void operation(String info)
    {
        //调用相关表达式类的解释方法
    }
}

Guess you like

Origin www.cnblogs.com/tuofan/p/12391506.html