The interpreter mode of Java and mode

Source: Internet
Author: User

The interpreter pattern is the behavior pattern of the class. Given a language, the interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. The client can use this interpreter to interpret the sentences in the language.

structure of the interpreter pattern

  The following is an example of a schematic system that discusses the structure of the interpreter pattern. The structure diagram of the system is as follows:

The roles involved in the pattern are as follows:

  (1) Abstract expression role: declares an abstract interface that all specific expression roles need to implement. This interface is primarily a interpret () method, which is called an interpretation operation.

  (2) The Terminator expression (Terminal expression) role: implements the interface required by the abstract expression role, mainly a interpret () method; each terminator in the grammar has a specific end expression corresponding to it. For example, there is a simple formula R=R1+R2, in which R1 and R2 are terminator, corresponding parsing R1 and R2 of the interpreter is the Terminator expression.

  (3) Non-terminator expressions (nonterminal expression) role: Each rule in the grammar requires a specific non-terminator expression, the non-terminator expression is generally the operator in the grammar or other keywords, such as the formula R=R1+R2, "+ "is non-terminator, parsing" + "interpreter is a non-terminator expression.

  (4) environment (context) Role: The task of this role is generally used to store the grammar of the individual terminator corresponding to the specific values, such as R=R1+R2, we give the R1 value of 100, to R2 assigned value 200. This information needs to be stored in the environment role, and in many cases it is sufficient for us to use map to act as an environment role.

  To illustrate the implementation of the interpreter pattern, here is the simplest syntax and the implementation of the corresponding interpreter pattern, which is to manipulate and evaluate Boolean expressions in the simulated Java language.

In this language, Terminator is a Boolean variable, which is the constant true and false. Non-terminator expressions contain Boolean expressions such as operators and,or and not. This simple grammar is as follows:

Expression:: = Constant | Variable | Or | and | Not

And:: = Expression ' and ' expression

Or:: = expression ' or ' expression

Not:: = ' not ' Expression

Variable:: = any identifier

Constant:: = ' true ' | ' False '

The structure diagram for the interpreter pattern is as follows:

  

Source

Abstract expression Role

Public abstract class Expression {    /**     * is subject to the environment, this method interprets any one given expression,     *    /Public Abstract Boolean interpret ( Context ctx);    /**     * Verify that two expressions are structurally identical     *    /Public abstract Boolean equals (Object obj);    /**     * Return expression hash code     */Public    abstract int hashcode ();    /**     * Converts an expression to a string     *    /Public abstract string toString ();

A constant object represents a Boolean constant

public class Constant extends expression{        private boolean value;    Public Constant (Boolean value) {        this.value = value;    }        @Override public    boolean equals (Object obj) {                if (obj! = null && obj instanceof Constant) {            return this . Value = = ((Constant) obj). value;        }        return false;    }    @Override public    int hashcode () {        return this.tostring (). Hashcode ();    }    @Override Public    Boolean interpret (Context ctx) {                return value;    }    @Override Public    String ToString () {        return new Boolean (value). ToString ();    }    }

A variable object represents a well-known variable

public class Variable extends Expression {    private String name;    Public Variable (String name) {        this.name = name;    }    @Override public    boolean equals (Object obj) {                if (obj! = null && obj instanceof Variable)        {            Return This.name.equals ((                    (Variable) obj). name);        }        return false;    }    @Override public    int hashcode () {        return this.tostring (). Hashcode ();    }    @Override public    String toString () {        return name;    }    @Override Public    Boolean interpret (Context ctx) {        return ctx.lookup (this);}    }

Represents the and class of the logical and operation, representing the operation of a new Boolean expression given by two Boolean expressions through the logical "and" Operation

public class and extends expression {    private expression left,right;        Public and (expression left, expression right) {        this.left = left;        This.right = right;    }    @Override public    boolean equals (Object obj) {        if (obj! = null && obj instanceof and)        {            return left . Equals (((and) obj). left) &&                Right.equals (((and) obj);        }        return false;    }    @Override public    int hashcode () {        return this.tostring (). Hashcode ();    }    @Override Public    Boolean interpret (Context ctx) {                return Left.interpret (CTX) && Right.interpret (CTX );    }    @Override public    String toString () {        return "(" + left.tostring () + "and" + right.tostring () + ")";    }}

Represents the or class of a logical OR operation, representing the operation of a new Boolean expression given by a two Boolean expression by a logical OR operation

public class Or extends expression {    private expression left,right;    Public Or (expression left, expression right) {        this.left = left;        This.right = right;    }    @Override public    boolean equals (Object obj) {        if (obj! = null && obj instanceof Or)        {return this            . Left.equals ((or) obj). left) && this.right.equals (((or) obj);        return false;    }    @Override public    int hashcode () {        return this.tostring (). Hashcode ();    }    @Override Public    Boolean interpret (Context ctx) {        return Left.interpret (CTX) | | Right.interpret (CTX);    @Override public    String toString () {        return "(" + left.tostring () + "OR" + right.tostring () + ")";    }}

The not class that represents the logical "not" operation, which represents the operation of a new Boolean expression given by a Boolean expression through a logical "non" operation

public class not extends expression {    private expression exp;        Public not (Expression exp) {        THIS.EXP = exp;    }    @Override public    boolean equals (Object obj) {        if (obj! = null && obj instanceof not)        {            return exp. Equals ((not                    ) obj). exp);        }        return false;    }    @Override public    int hashcode () {        return this.tostring (). Hashcode ();    }    @Override Public    Boolean interpret (Context ctx) {        return!exp.interpret (CTX);    }    @Override public    String toString () {        return ' (not ' + exp.tostring () + ') ';    }}

The environment (context) class defines a mapping from a variable to a Boolean value

public class Context {    private map<variable,boolean> Map = new hashmap<variable,boolean> ();        public void assign (Variable var, boolean value) {        map.put (Var, new Boolean (value));    }        Public Boolean lookup (Variable var) throws illegalargumentexception{        Boolean value = Map.get (Var);        if (value = = null) {            throw new illegalargumentexception ();        }        return Value.booleanvalue ();    }}

Client class

public class Client {public    static void Main (string[] args) {        context ctx = new Context ();        Variable x = new Variable ("X");        Variable y = new Variable ("Y");        Constant C = new Constant (true);        Ctx.assign (x, false);        Ctx.assign (Y, true);                Expression exp = new Or (new and (C,x), new and (Y,new not (x)));        System.out.println ("x=" + X.interpret (CTX));        System.out.println ("y=" + Y.interpret (CTX));        System.out.println (exp.tostring () + "=" + Exp.interpret (CTX));}    }

The results of the operation are as follows:

The interpreter mode of Java and mode

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.