Design Patterns twenty-three: Interpreter mode (Interpreter)

In software development, we will encounter some problems repeatedly occur, and there is a certain similarity and regularity. If they are grouped into a simple language, these issues will be Examples of some sentences of the language, so that you can use the "compiler theory" in the interpreter mode to achieve.

Although examples using an interpreter mode is not a lot, but to meet the above characteristics, and operating efficiency is not very high application example, if the interpreter mode is implemented, the effect is very good, this article will introduce their works and Instructions.

The definition and characteristics of the model

Defined interpreter (Interpreter) mode: to analyze a language object definition, and the definition of the language grammar, said re-design a parser to interpret the language of the sentence. In other words, a compiled language to analyze examples of applications. This expression grammar model implements the interface process, a specific explanation of the interface context.

The concept of grammar and sentence mentioned here in the same compiler theory to describe the same, "grammar" refers to the grammatical rules of the language, and "sentence" is the focus of language elements. For example, there are many Chinese sentence, "I am Chinese" is one sentence, you can use a syntax tree to visually describe the sentences in the language.

Interpreter pattern is a type of model classes, the following major advantages.

  1. Good scalability. The use of classes in the interpreter mode represented grammar rules of a language and the grammar may be changed or extended by inheritance mechanisms.
  2. easy to accomplish. Each class in the expression node in the syntax tree are similar, it is relatively easy to achieve its grammar.


The main drawback of mode explained below.

  1. The lower the efficiency. Interpreter pattern commonly used in a large number of cycles and recursive calls, when to explain more complex sentences, its speed is very slow, and the process of debugging the code too much trouble.
  2. Class will cause swelling. Each Rule Interpreter mode define at least a class, when the grammar rule contains many, the number of classes will increase sharply, resulting in system management and maintenance difficult.
  3. Applicable scene is relatively small. In software development, application examples need to define the language grammar is very small, so this mode is rarely used to.

Architecture and Implementation Model

Interpreter pattern commonly used in compiling or analyzing examples of simple language in order to master its structure and implementation, we must first understand the translation principle of "grammar, sentence syntax tree" and other related concepts.

1) grammar

Formal rules of grammar is used to describe the grammatical structure of the language. No rules no standards, for example, some people think the guidelines are perfect love "mutual attraction, emotional specificity, neither party experienced love", although the last one criterion more demanding, but anything else, there are rules, language, too, Whether it is a machine language or natural language with its own grammar rules. For example, the Chinese in the "sentence" grammar follows. 

〈句子〉::=〈主语〉〈谓语〉〈宾语〉
〈主语〉::=〈代词〉|〈名词〉
〈谓语〉::=〈动词〉
〈宾语〉::=〈代词〉|〈名词〉
〈代词〉你|我|他
〈名词〉7大学生I筱霞I英语
〈动词〉::=是|学习

Note: the notation ":: =" means "is defined as" means, with the "<" and ">" non-terminal symbol enclose, surround is no terminator.

2) sentence

Sentence is the basic unit of language, the language is a set of elements, which consists of a terminator can be derived from "grammar." For example, the above grammar can be introduced, "I is a college student," so it is a sentence.

3) syntax trees

The syntax tree is a tree structure of a sentence, it represents the derivation result of the sentence, it is useful in understanding the level of grammatical structure of sentences. Figure 1 is "I am a university student," the syntax tree.
 

                                       The sentence "I am a university student," the syntax tree
1 sentence "I am a university student," the syntax tree


With these basics, now to introduce the structure of the interpreter pattern is simple. Structure and mode of interpretation combination pattern similar, but it contains constituent elements than the combination pattern, and a combination of structural model is an object model, is interpreted mode class type of model.

1. Structure Model

Interpreter pattern consists of the following major role.

  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 .


Interpreter pattern configuration diagram shown in Figure 2.
 

            Mode of the structure of FIG explained

2. Mode of realization

Key interpretation mode is implemented grammar rules define the design classes and terminator nonterminal class, the structure shown in FIG constructed syntax tree if necessary, the code structure is as follows:

//抽象表达式类
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)
    {
        //调用相关表达式类的解释方法
    }
}

 

Mode of application examples

[Example 1] design a "Shao Unitoll" bus card with the card reader mode interpreter program.

Description: If "Shao Yue Tong" card reader can determine the identity of the bus passengers, if it is "Shaoguan" or "Canton" and "elderly" "Women," "child" can be a free ride, others ride a buckle 2 yuan.

Analysis: This example of "interpretation mode" is more suitable design, the first design which follows the grammar rules.

<expression> ::= <city>的<person>
<city> ::= 韶关|广州
<person> ::= 老人|妇女|儿童

Then, according to the rules of grammar class diagram design of bus card reader program, follow these steps.

  • Define an abstract expression (Expression) interface, which contains the interpretation interpret (String info).
  • Expression defines a terminator (Terminal Expression) class, with which set (the Set) or human class to hold the city to meet the conditions, and to achieve an abstract expression interpretation interface interpret (Stringinfo), the character is determined to be analyzed whether strings are set terminator.
  • Terminator expression object personnel terminator expression object and satisfy the conditions of the definition of a non-terminal expression (AndExpressicm) class, which is a subclass of abstract expression, which includes the condition of the city, and to achieve interpret (String info) method, used to determine whether the string is analyzed to meet the conditions of persons satisfying the condition in the city.
  • Finally, the definition of an environment (Context) class, which contains the data interpreter needed to complete initialization of the terminator of the expression, and defines a method of interpretation freeRide (String info) to call the character string expression object to be analyzed explained. The structure shown in Figure 3.

 

                   Structure map "Shao Yue Tong" Bus Reader program


Code is as follows:

package interpreterPattern;
import java.util.*;
/*文法规则
  <expression> ::= <city>的<person>
  <city> ::= 韶关|广州
  <person> ::= 老人|妇女|儿童
*/
public class InterpreterPatternDemo
{
    public static void main(String[] args)
    {
        Context bus=new Context();
        bus.freeRide("韶关的老人");
        bus.freeRide("韶关的年轻人");
        bus.freeRide("广州的妇女");
        bus.freeRide("广州的儿童");
        bus.freeRide("山东的儿童");
    }
}
//抽象表达式类
interface Expression
{
    public boolean interpret(String info);
}
//终结符表达式类
class TerminalExpression implements Expression
{
    private Set<String> set= new HashSet<String>();
    public TerminalExpression(String[] data)
    {
        for(int i=0;i<data.length;i++)set.add(data[i]);
    }
    public boolean interpret(String info)
    {
        if(set.contains(info))
        {
            return true;
        }
        return false;
    }
}
//非终结符表达式类
class AndExpression implements Expression
{
    private Expression city=null;    
    private Expression person=null;
    public AndExpression(Expression city,Expression person)
    {
        this.city=city;
        this.person=person;
    }
    public boolean interpret(String info)
    {
        String s[]=info.split("的");       
        return city.interpret(s[0])&&person.interpret(s[1]);
    }
}
//环境类
class Context
{
    private String[] citys={"韶关","广州"};
    private String[] persons={"老人","妇女","儿童"};
    private Expression cityPerson;
    public Context()
    {
        Expression city=new TerminalExpression(citys);
        Expression person=new TerminalExpression(persons);
        cityPerson=new AndExpression(city,person);
    }
    public void freeRide(String info)
    {
        boolean ok=cityPerson.interpret(info);
        if(ok) System.out.println("您是"+info+",您本次乘车免费!");
        else System.out.println(info+",您不是免费人员,本次乘车扣费2元!");   
    }
}

 Program results are as follows:

您是韶关的老人,您本次乘车免费!
韶关的年轻人,您不是免费人员,本次乘车扣费2元!
您是广州的妇女,您本次乘车免费!
您是广州的儿童,您本次乘车免费!
山东的儿童,您不是免费人员,本次乘车扣费2元!

Application of scene modes

The structure and characteristics of the foregoing explanation mode, the following analysis of its application scenario.

  1. When the grammar of the language is simple and the implementation of efficiency is not the key problem.
  2. When the problem recurs, and can use a simple language to express the time.
  3. When a desired language interpreted, and sentences in the language can be expressed as an abstract syntax tree, such as XML document explains.


Note: Interpreter pattern used in the actual software development is relatively small, because it will lead to efficiency, performance, and maintenance issues. If you hit the interpretation of the expressions in  Java  can be used such as Expression4J or Jep design.

Extended mode

In project development, if you want to be an expression data analysis and calculation, will not take the interpreter mode design, Java provides the following powerful mathematical formula parser: Expression4J, MESP (Math Expression String Parser) and Jep, etc. they can explain some complex grammar, powerful, easy to use.

Jep now an example to introduce the use of the toolkit. Jep is a Java expression parser short, that Java expression parser, which is used to convert a mathematical expression and calculate the Java library. By this library, the user may input an arbitrary formula as a string, then rapidly calculate its result. And Jep supports user-defined variables, constants and functions, which includes many common mathematical functions and constants.

Download Jep before use compressed package, unpacked, will jep-xxxjar files to a directory of your choice, select "Add external JAR (X) in Eclipse's" Java Build Path "dialog" Library "tab .. . ", the package is added after Jep project to use one of the library.

Below to calculate interest on deposits as an example to introduce. Deposit interest is calculated: Principal Rate x Time = x interest, the relevant code is as follows:

package interpreterPattern;
import com.singularsys.jep.*;
public class JepDemo
{
    public static void main(String[] args) throws JepException
    {
        Jep jep=new Jep();
        //定义要计算的数据表达式
        String 存款利息="本金*利率*时间";
        //给相关变量赋值
        jep.addVariable("本金",10000);
        jep.addVariable("利率",0.038);
        jep.addVariable("时间",2);
        jep.parse(存款利息);    //解析表达式
        Object accrual=jep.evaluate();    //计算
        System.out.println("存款利息:"+accrual);
    }
}

 Program results are as follows:

存款利息:760.0

 

 

 

 

 

 

Published 136 original articles · won praise 6 · views 1536

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/104437918