Design mode-Interpreter mode

Source: Internet
Author: User

Go directly to the topic, interpreter UML diagram

As you can see from the UML diagram

The core is the Abstractexpression class, which is the abstraction layer of the interpreter. His core approach is interpret (Content)

OK, now we can think, how to write an interpreter?

I usually start thinking about this.

Pseudo code

Step1: The kernel method's entry is a content class, so let's create a content class first.

Step2: Writes an interface or abstract class expression abstract method interpret (Content).

Step3: Implements abstract class expression abstract method interpret (Content).

So we're trying to write an addition and subtraction of numbers within 10.

Create a content class

 Public classContent {//input    Private Char[] inputs; //Results    Private intResult=0; //pointer Markers    Private intMark=0; //Digital Queue    PrivateArrayblockingqueue<integer> Numqueque =NewArrayblockingqueue<integer> (20); //symbol Queue    PrivateArrayblockingqueue<character> Optqueque =NewArrayblockingqueue<character> (20);  PublicContent (Char[] inputs) {         This. inputs =inputs; }

Here I use two queue to separate save instructions (I divided into digital instructions and operation instructions) for the subsequent calculator can be convenient to take the value of the operation

However, it is not very convenient to initialize the content class, so I wrote a Gammarparser class to initialize and detect the syntax.

 Public classGammarparse {PrivateString numerror= "Numeric error:"; PrivateString opterror= "Symbol Error:";  PublicContent parsetocontent (String str)throwsparseexception, interruptedexception{content content=NewContent (Str.tochararray ());        Pushconentoptandnumqueque (content); returncontent; }        /*** Press the input into the content Queque *@paramcontent *@throwsParseException *@throwsinterruptedexception*/     Public voidPushconentoptandnumqueque (content content)throwsParseException, interruptedexception{ for(Charc:content.getinputs ()) {            if(Content.getmark ()%2==0) {//flag bit is either even or numericTry{content.getnumqueque (). Put (Integer.parseint (string.valueof (c))); } Catch(Exception e) {Throw NewParseException (numerror+c); }            }Else{Grammarcheck (c);            Content.getoptqueque (). put (c); } Content.setmark (Content.getmark ()+1); }    }        /*** Symbol Checker *@paramc *@throwsparseexception*/    Private voidGrammarcheck (CharCthrowsparseexception{if(! (c== ' + ' | | c== '-')){            Throw NewParseException (opterror+c); }    }    }

Write an interface or abstract class expression abstract method interpret (Content).

 Public Interface interperter {    void  interperter (content content);}

Implements the class Calcinterperter of abstract class expression abstract method interpret (Content).

 Public classCalcinterperterImplementsinterperter{@Override Public voidInterperter (content content) {Content.setresult (Content.getnumqueque (). poll ());//The first digital queue is directly assigned to result /c12> while(!Content.getnumqueque (). IsEmpty ()) {            Switch(Content.getoptqueque (). Poll ()) { Case+: Content.setresult (Content.getresult ()+Content.getnumqueque (). poll ());  Break;  Case‘-‘: Content.setresult (Content.getresult ()-Content.getnumqueque (). poll ());  Break; default:                 Break; }        }    }}

Here I judge the number of the queue is not empty then the numbers out of the team at the same time with the symbol team list the elements of the team to calculate.

OK, the addition and subtraction calculator in the simple 1-10 is done. Let's run the unit test.

 Public classClient {@Test Public voidTest ()throwsParseException, interruptedexception{List<String> expresses =NewArraylist<string>(); Expresses.add ("1+2"); Expresses.add ("1+2+3"); Expresses.add ("1+2+5"); Expresses.add ("1+2-3"); Expresses.add ("1+2-9"); Expresses.add ("1+2-8+2"); Gammarparse Paser=NewGammarparse (); Calcinterperter Calc=NewCalcinterperter ();  for(String exp:expresses) {content content=paser.parsetocontent (exp);            Calc.interperter (content); SYSTEM.OUT.PRINTLN (exp+" = "+Content.getresult ()); }    }}
1+2 = 31+2+3 = 61+2+5 = 81+2-3 = 01+2-9 = -61+2-8+2 =-3

Design mode-Interpreter mode

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.