Interpreter mode, that is, Interpreter mode.
The interpreter mode is a behavior mode. The Gof defines a language, a syntax expression, and an interpreter. This interpreter uses this expression to describe the language.
Explain sentences in a language.
What needs to be solved in the interpreter mode is that if a specific type of problem occurs frequently enough, it may be worth expressing each instance of the problem as a sentence in a simple language]
. In this way, an interpreter can be built to solve the problem by interpreting these sentences.
Instance application: Regular Expression
Example:
[Java]
Package design. interpreter;
/**
* File name: Context. java
* Created by: Fei Wong
* Created at: Jun 25,201 2
* Email: www.2cto.com
* Interpreter context environment. It is used to store the context of the interpreter, such as the grammar to be interpreted.
**/
Public class Context {
Private String in;
Private int out;
Public Context (String in ){
This. in = in;
}
Public int getOut (){
Return out;
}
Public void setOut (int out ){
This. in = String. valueOf (out );
This. out = out;
}
Public String getIn (){
Return in;
}
}
Package design. interpreter;
/**
* File name: AbstractExpression. java
* Created by: Fei Wong
* Created at: Jun 25,201 2
* Email: www.2cto.com
* The Interpreter abstract class.
**/
Public abstract class extends actexpression {
Public abstract void interpret (Context context );
}
Package design. interpreter;
/**
* File name: MinusExpression. java Creator: Fei Wong Creation Time: Jun 25,201 2
* Email: www.2cto.com
* Explains the implementation class of the appliance body.
*/
Public class MinusExpression extends actexpression {
@ Override
Public void interpret (Context context ){
String in = context. getIn ();
Int v = Integer. parseInt (in );
Context. setOut (-- v );
}
}
Package design. interpreter;
/**
* File name: PlusExpression. java
* Created by: Fei Wong
* Created at: Jun 25,201 2
* Email: www.2cto.com
* Explains the implementation class of the appliance body.
**/
Public class PlusExpression extends actexpression {
@ Override
Public void interpret (Context context ){
String in = context. getIn ();
Int v = Integer. parseInt (in );
Context. setOut (++ v );
}
}
Package design. interpreter;
/**
* File name: Client. java
* Created by: Fei Wong
* Created at: Jun 25,201 2
* Email: www.2cto.com
**/
Public class Client {
/**
* @ Param args
*/
Public static void main (String [] args ){
Context context = new Context ("10 ");
New MinusExpression (). interpret (context );
New PlusExpression (). interpret (context );
New MinusExpression (). interpret (context );
New PlusExpression (). interpret (context );
System. out. println (context. getOut ());
}
}
Author: hfmbook