Java-based interpreter design pattern

Source: Internet
Author: User
Tags abstract constant expression implement integer
Design One, primer

In fact, there is no good example to introduce the interpreter pattern, because it describes how to form a simple language interpreter, the main application in the use of object-oriented language development compiler; In practical applications, we may rarely encounter the syntax to construct a language.

Although you can hardly use this model, it is still possible to get some inspiration from the look.

II. Definition and structure

The interpreter pattern is defined as follows: Defines the grammar of a language and creates an interpreter to interpret the sentences in that language. It belongs to the behavior pattern of the class. The language here means code that uses the prescribed format and syntax.

In Gof's book: If a particular type of problem occurs frequently enough, it may be worthwhile to express each instance of the problem as a sentence in a simple language. This allows you to build an interpreter that interprets the sentences to solve the problem. And it works best when the grammar is simple and efficiency is not the key issue.

This is also the context in which the interpreter pattern is applied.

Let's see what the mystery of the interpreter model is made of.

1 Abstract expression role: declares an abstract interpretation operation, which is implemented for all concrete expression roles (nodes in the abstract syntax tree).

What is called an abstract syntax tree? The explanation given in Java and schema is that each node of the abstract syntax tree represents a statement, and the interpretation method can be performed on each node. The execution of this interpretation method means that the statement is interpreted. Because each statement represents this statement is interpreted. Because each statement represents an instance of a common problem, the interpretation operation on each node represents the answer to an instance of the problem.

2 non-terminal expression role: concrete expression.

A) Implementation of interpretation operations associated with non-terminal in the grammar

b) and each non-terminal in the sentence requires an instance of the class to correspond to it

3 non-non-terminal expression role: concrete expression.

(a) Each rule in the grammar r::=r1r2 ... RN needs a non non-terminal strap type role

B to maintain an abstract expression role's instance variable for each symbol from R1 to RN

(c) Implementation of interpretation operations, interpretation generally to recursively invoke the interpretation of those objects from R1 to RN

4) context (Environment) role: contains some global information outside the interpreter.

5) Customer Role:

(a) constructs (or is given) an abstract syntax tree that represents a particular sentence in the language defined by the grammar

b) invoke an interpretation operation

Put on the Interpreter structure class diagram, which is also from the Gof book.



Detailed responsibilities are given for each role, and the relationship between the five roles is given in the class diagram. This is not very difficult to implement, and here is a simple example, hoping to deepen your understanding of the interpreter model.

Iii. examples

To give a subtraction example, the idea comes from the example in Java and schema. The functions of each role are implemented according to the specification mentioned above.

Context (Environment) role, using HashMap to store values for variables

Class context
{
Private Map ValueMap = new HashMap ();
public void AddValue (Variable x, int y)
{
Integer yi = new Integer (y);
Valuemap.put (x, Yi);
}

public int LookupValue (Variable x)
{
int i = ((Integer) valuemap.get (x)). Intvalue ();
return i;
}
}

Abstract expression role, or you can use an interface to implement

Abstract class Expression
{
public abstract int interpret (context con);
}

Non-terminal expression role

Class Constant extends Expression
{
private int i;
Public Constant (int i)
{
THIS.I = i;
}

public int interpret (context con)
{
return i;
}
}

Class Variable extends Expression
{
public int interpret (context con)
{
This is the variable object that calls the interpret method
Return con. LookupValue (this);
}
}

Non-non-terminal expression role

Class Add extends Expression
{
Private Expression left, right;
Public Add (Expression left, Expression right)
{
This.left = left;
This.right= right;
}

public int interpret (context con)
{
return Left.interpret (Con) + Right.interpret (con);
}
}

Class Subtract extends Expression
{
Private Expression left, right;
Public subtract (Expression left, Expression right)
{
This.left = left;
This.right= right;
}

public int interpret (context con)
{
return Left.interpret (Con)-right.interpret (con);
}

}

Class Multiply extends Expression
{
Private Expression left, right;
Public Multiply (Expression left, Expression right)
{
This.left = left;
This.right= right;
}
public int interpret (context con)
{
return Left.interpret (Con) * Right.interpret (con);
}
}

Class Division extends Expression
{
Private Expression left, right;
Public Division (Expression left, Expression right)
{
This.left = left;
This.right= right;
}

public int interpret (context con)
{
try{
return Left.interpret (Con)/Right.interpret (con);
}catch (ArithmeticException AE)
{
System.out.println ("The divisor is 0!") ");
return-11111;
}
}
}

Test procedures, calculations (A*B)/(a-b+2)

public class Test
{
private static Expression ex;
private static context con;
public static void Main (string[] args)
{
con = new context ();
Set variables, constants
Variable a = new Variable ();
Variable B = new Variable ();
Constant C = new Constant (2);
Assigning values to variables
Con.addvalue (A, 5);
Con.addvalue (b, 7);
operation, the structure of the sentence is analyzed by ourselves, constructed
ex = new Division (new Multiply (A, B), new Add (new Subtract (A, b), c));
SYSTEM.OUT.PRINTLN ("The result of the operation is:" +ex.interpret (Con));
}
}

The interpreter pattern does not show how to create an abstract syntax tree, so it can be implemented in a variety of ways, which we provide directly in test and, of course, better and more professional implementations.

For non-terminal, it is recommended that the GOF pattern be used to share their copies because they appear repeatedly. However, given the limitations of the use of the meta pattern, I recommend that you consider the non-terminal mode when you have enough repetition in your system.

Iv. Advantages and Disadvantages

The interpreter pattern provides a simple way to perform syntax, and it is easy to modify or extend the syntax. Many classes in a general system use similar syntax, and an interpreter can be used instead of implementing an interpreter for each rule. and the different rules in the interpreter are implemented by different classes, making it easy to add a new syntax rule.

But the interpreter model is difficult to maintain for complex grammars. It can be imagined that each rule corresponds to a processing class, and that these classes also recursively call the abstract expression role, how horrible it is to be intertwined with a tangled class!

V. Summary

This should have some general understanding of the interpreter model, because this model uses a few cases, so the majority of the views of this article directly from the original GOF. Only the instance code is implemented in person and debugged through.



Related Article

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.