Java-based interpreter Design Mode

Source: Internet
Author: User
   I. Introduction

In fact, there is no good example to introduce the interpreter mode, because it describes how to form a simple language interpreter, mainly used in the use of object-oriented language development compilers; in practical applications, we may rarely encounter the situation of constructing a language grammar.

Although you can hardly use this model, you can still be inspired by it.

  Ii. Definition and Structure

The interpreter mode is defined as follows: defines the grammar of a language and creates an interpreter to explain sentences in the language. It belongs to the behavior mode of the class. The language here refers to the code that uses the specified format and syntax.

In the gof book, it is pointed out 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. In addition, it works best when grammar is simple and efficiency is not a key issue.

This is the interpreter application environment.

Let's take a look at what the mysterious interpreter mode is composed.

1) Abstract Expression role: declares an abstract interpretation operation. This interface must be implemented for all specific expression roles (nodes in the abstract syntax tree.

What is the abstract syntax tree? In Java and mode, each node in the abstract syntax tree represents a statement, and each node can execute an interpretation method. The execution of this interpretation method indicates that this statement is interpreted. Each statement indicates that this statement is interpreted. Since each statement represents an instance of a common problem, the explain operation on each node represents a solution to a problem instance.

2) Terminator expression role: a specific expression.

A) implements interpretation operations associated with terminator in grammar

B) and each terminator in a sentence needs an instance of the class to correspond to it.

3) Non-terminator expression role: Specific Expression.

A) each rule in the grammar R: = r1r2... Rn requires a non-terminator strap-type role.

B) Maintain an instance variable of the abstract expression role for each symbol from R1 to rn.

C) Implement the interpretation operation. The interpretation usually involves recursively calling the interpretation operation of the objects from R1 to rn.

4) Context (Environment) Role: Contains global information other than the interpreter.

5) customer role:

A) construct (or be given) the abstract syntax tree of a specific sentence in the language defined by the syntax.

B) Call the interpretation operation

Put the structure diagram of the interpreter on the top, which is also from the gof book.

Each role is given detailed responsibilities, and the relationship between the five roles is given in the class diagram. This is not very difficult to implement. The following is a simple example, hoping to deepen your understanding of the interpreter mode.

  Iii. Example

Here is an example of addition, subtraction, multiplication, and division. The implementation idea comes from the example in Java and mode. The functions of each role are implemented according to the specifications mentioned above.

// Context (Environment) role, which uses hashmap to store the value corresponding to the variable

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, which can also be implemented using interfaces

Abstract class expression
{
Public abstract int interpret (context con );
}

// Terminator 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-terminator 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 the program, calculate (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 and constants
Variable A = new variable ();
Variable B = new variable ();
Constant c = new constant (2 );
// Assign values to variables
Con. addvalue (A, 5 );
Con. addvalue (B, 7 );
// Operation. We analyze and construct the sentence structure by ourselves.
Ex = new Division (New multiply (a, B), new add (New subtract (a, B), c ));
System. Out. println ("Calculation Result:" + ex. interpret (CON ));
}
}

The interpreter mode does not explain how to create an abstract syntax tree. Therefore, its implementation can be varied. We provide it directly in test, of course, there are also better and more professional implementation methods.

For Terminator, gof recommends that you use the metadata mode to share their copies, because they must appear multiple times. However, considering the usage limitations of the Meta mode, we recommend that you consider the meta mode when there are enough terminologies repeated in your system.

  Iv. Advantages and Disadvantages

The interpreter mode provides a simple way to execute the syntax, and it is easy to modify or extend the syntax. In general, many classes in the system use similar syntaxes. You can use an interpreter to implement an interpreter for each rule. Different rules in the interpreter are implemented by different classes, which makes it easy to add a new syntax rule.

However, the interpreter mode is difficult to maintain complex grammar. It can be imagined that each rule corresponds to a processing class, and these classes also need to call the abstract expression role recursively. What a terrible thing is that many messy classes are intertwined!

  V. Summary

In this way, I should have a general understanding of the interpreter mode. Due to the lack of cases in this mode, most of the views in this article are directly from the original gof. Only the instance code is implemented and debugged in person.

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.