Interpreter mode (interpreter)

Source: Internet
Author: User

It is generally used in the development of the compiler in OOP development, so the application surface is rather narrow.

Public interface Expression {public int interpret (context context);}
public class Plus implements expression{@Overridepublic int interpret (context context) {//TODO auto-generated method stub Return Context.getnum1 () +context.getnum2 ();}}
public class minus implements expression{@Overridepublic int interpret (context context) {//TODO auto-generated method Stu Breturn context.getnum1 ()-context.getnum2 ();}}
public class Context {private int num1, Num2;public int getNum1 () {return NUM1;} public int getNum2 () {return num2;} public void setNum1 (int num) {this.num1 = num;} public void setNum2 (int num) {this.num2 = num;} Public Context (int num1, int num2) {this.num1 = num1;this.num2 = num2;}}

Test class:

/** * Parser Mode * @author Administrator * */public class Test {public static void main (string[] args) {//TODO auto-generated Method stub//Calculates 9+8-7int result = new minus (). Interpret (new context (new Plus (). Interpret (new context (9, 8)), 7)  ));  SYSTEM.OUT.PRINTLN (result); }}

Final output correct result: 10

Basically, the interpreter pattern is used to make all kinds of interpreters, such as regular expressions and so on!


Interpreter mode (interpreter)

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.