JAVA design mode-interpreter mode (interpreter) __java

Source: Internet
Author: User
Tags arithmetic

definition: Given a language, defines a representation of his grammar, and defines an interpreter that uses the representation to interpret a sentence in a language.

Type: class behavior pattern

class Diagram:

The structure abstraction interpreter of the interpreter pattern : declares an abstract interface (or abstract class) to be implemented for all concrete expressions, and is primarily a interpret () method, called an interpretation operation. The specific interpretation task is accomplished by its various implementation classes, and the concrete interpreters are completed by the Non-terminal interpreter Terminalexpression and the Non-terminal interpreter nonterminalexpression respectively. Non-terminal expression: Implements an interpretation operation associated with an element in a grammar, usually with only one non-terminal expression in an interpreter pattern, with multiple instances corresponding to different terminators.                                 Non-terminal is half the arithmetic unit in the grammar, for example, there is a simple formula R=R1+R2, in which R1 and R2 are non-terminal, the corresponding parsing R1 and R2 interpreter is the non-terminal expression. Non-non-terminal expressions: Each rule in a grammar corresponds to a non-terminal expression, and a non-terminal expression is generally an operator or other keyword in a grammar, such as a formula R=R1+R2, + is not a non-terminal, and an interpreter for parsing + is a non-non-terminal expression. Non-non-terminal expressions increase according to the complexity of the logic, in principle each grammar rule corresponds to a non-terminal expression. Environment role: The task of this role is generally used to store the specific values of each non-terminal in the grammar, such as R=R1+R2, we give the R1 value 100, to R2 assigned a value of 200. This information needs to be stored in the environment role, and in many cases it is sufficient that we use the map to act as an environmental role.


Code Implementation

Contextual environment
class Context {
	
}

An abstract expression

Abstract class Expression {
	
	//each expression must have a parse task public
	abstract Object Interpreter (context ctx);
}


Abstract expressions are the key to generating a collection of grammars (also known as a syntax tree), each of which completes the specified parsing task by recursive invocation and ultimately by the smallest syntactic unit.


Non-terminal expression

Class Terminalexpression extends Expression {
	
	//usually there is only one non-terminal expression, but there are multiple objects public Object
	Interpreter (context ctx) { C9/>return null;
	}
}


Usually, the non-terminal expression is simpler, mainly dealing with the transformation of scene elements and data.


Non-non-terminal expressions

Class Nonterminalexpression extends Expression {
	
	//each non-non-terminal expression produces dependent public nonterminalexpression on other Expressions
	( Expression. Expressions) {} public

	Object Interpreter (context ctx) {
		
		//grammar processing return
		
		null;
	}
}

Each of the non-terminal expressions represents a grammar rule, and each grammar rule is concerned only with the result of the grammatical rules of its own periphery (attention is the result), so this produces a non-terminal expression that calls its own periphery, and then the final, smallest grammatical rule is the non-terminal expression, The concept of non-terminal expressions is so that it is not possible to participate in the grammar operations smaller than yourself.


Customer Class Code

public class Client {

	/**
	 * @param args
	 *
	/public static void main (string[] args) {context
		
		CTX = n EW context ();
		 
		Typically, a syntax container is set, accommodating a specific expression, usually a listarray,linkedlist,stack type
		 
		stack<expression> Stack = null; 
		 
		for (;;) {
		 
		//make grammatical judgments and generate recursive calls
		 
		}
		 
		//Generate a complete syntax tree, which is parsed by each specific parsing
		 
		Expression exp = Stack.pop ();
		 
		Concrete elements into the scene
		 
		Exp.interpreter (CTX);

		
	}


Usually the client is a encapsulated class, the result of the encapsulation is passed in a canonical grammar file, parser analysis produces the result and returns, avoids the caller and the parser coupling relationship.


the pros and cons of the interpreter pattern

Advantages:

Interpreter is a simple syntax analysis tool, its most significant advantage is extensibility, modify the grammar rules as long as the corresponding non-terminal expression can be modified, if extended syntax, it is only to increase the Non-terminal class.

Disadvantages:

The interpreter pattern causes the class to swell. Each syntax has to produce a non-terminal expression, the syntax rules are more complex, it may produce a large number of class files, for maintenance brings a lot of trouble.

The interpreter pattern uses recursive invocation methods each non-terminal expression is concerned only with expressions of its own concern, each expression needs to know the final result, must peel the cocoon layer by layer, whether it is a process-oriented language or an object-oriented language, recursion is used under the necessary conditions, which results in very complex debugging. Think about it, if you want to troubleshoot a grammatical error, we are not going to have to debug a breakpoint until the smallest syntax unit.

Efficiency problem interpreter model due to the use of a large number of loops and recursion, efficiency is a problem that can not be ignored, especially for the resolution of complex, lengthy syntax, the efficiency is unbearable.


Applicable Scenarios

Recurring problems can be used in interpreter mode for example, multiple application servers generate a large number of logs every day, need to analyze the log files, because the log format of each server is different, but the data elements are the same, according to the interpreter is the non-terminal expression is the same, But non-non-terminal expressions need to be developed. In this case, the program can be used to solve the problem once and for all.

A simple grammar needs to explain why the scene is simple. Look at the non-final expression, the more grammar rules, the higher the complexity, and the recursive call between classes (see the stack in our example), not generally complex. Think about the calls between multiple classes what kind of patience and confidence you need to troubleshoot problems. Thus, the interpreter pattern is typically used to parse a standard character set, such as SQL parsing, but the part is gradually replaced by a dedicated tool.


In some particular business environment will also adopt the interpreter mode, we just have a business environment, and now there are so many examples of model operations, many business organizations have been able to provide a large number of data for analysis.


Attention Matters

Try not to use interpreter patterns in important modules, or maintenance can be a big problem. In your project, you can replace the interpreter pattern with Shell, JRuby, groovy, and other scripting languages to make up for the lack of Java-compiled language. We use JRuby in a Bank analytics project to avoid the use of interpreter mode arithmetic, efficiency and performance in all aspects of the good performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.