-------Interpreter for Java 23 design Patterns

Source: Internet
Author: User

One, interpreter mode (interpreter)
Interpreter mode is generally used in the development of the compiler in OOP development, so the application surface is narrower.

The context class is a contextual class, plus and minus are used to calculate the implementation, the code is as follows:

    1. Public interface Expression {
    2. public int interpret (context context);
    3. }
    1. public class Plus implements Expression {
    2. @Override
    3. public int interpret (context context) {
    4. Return Context.getnum1 () +context.getnum2 ();
    5. }
    6. }
    1. public class minus implements Expression {
    2. @Override
    3. public int interpret (context context) {
    4. Return Context.getnum1 ()-context.getnum2 ();
    5. }
    6. }
  1. public class Context {
  2. private int num1;
  3. private int num2;
  4. Public Context (int num1, int num2) {
  5. THIS.NUM1 = NUM1;
  6. this.num2 = num2;
  7. }
  8. public int getNum1 () {
  9. return NUM1;
  10. }
  11. public void setNum1 (int num1) {
  12. THIS.NUM1 = NUM1;
  13. }
  14. public int getNum2 () {
  15. return num2;
  16. }
  17. public void setNum2 (int num2) {
  18. this.num2 = num2;
  19. }
  20. }
    1. public class Test {
    2. public static void Main (string[] args) {
    3. Calculate the value of a 9+2-8
    4. int result = new minus (). Interpret (new Context (New Plus ()
    5. . Interpret (new Context (9, 2)), 8));
    6. SYSTEM.OUT.PRINTLN (result);
    7. }
    8. }

Finally output the correct result: 3.

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

Reprinted from Https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html

-------Interpreter for Java 23 design Patterns

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.