Interpreter Pattern: Calculator : Interpretor Pattern « Design Pattern « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Design Pattern » Interpretor PatternScreenshots 
Interpreter Pattern: Calculator
Interpreter Pattern: Calculator

/*

Software Architecture Design Patterns in Java
by Partha Kuchana 

Auerbach Publications

*/



import java.util.HashMap;
import java.util.Stack;

public class Calculator {
  private String expression;

  private HashMap operators;

  private Context ctx;

  public static void main(String[] args) {
    Calculator calc = new Calculator();
    //instantiate the context
    Context ctx = new Context();

    //set the expression to evaluate
    calc.setExpression("(a+b)*(c-d)");

    //configure the calculator with the
    // Context
    calc.setContext(ctx);

    //Display the result
    System.out.println(" Variable Values: " "a=" + ctx.getValue("a")
        ", b=" + ctx.getValue("b"", c=" + ctx.getValue("c")
        ", d=" + ctx.getValue("d"));
    System.out.println(" Expression = (a+b)*(c-d)");
    System.out.println(" Result = " + calc.evaluate());
  }

  public Calculator() {
    operators = new HashMap();
    operators.put("+""1");
    operators.put("-""1");
    operators.put("/""2");
    operators.put("*""2");
    operators.put("(""0");
  }

  public void setContext(Context c) {
    ctx = c;
  }

  public void setExpression(String expr) {
    expression = expr;
  }

  public int evaluate() {
    //infix to Postfix
    String pfExpr = infixToPostFix(expression);

    //build the Binary Tree
    Expression rootNode = buildTree(pfExpr);

    //Evaluate the tree
    return rootNode.evaluate(ctx);
  }

  private NonTerminalExpression getNonTerminalExpression(String operation,
      Expression l, Expression r) {
    if (operation.trim().equals("+")) {
      return new AddExpression(l, r);
    }
    if (operation.trim().equals("-")) {
      return new SubtractExpression(l, r);
    }
    if (operation.trim().equals("*")) {
      return new MultiplyExpression(l, r);
    }

    return null;
  }

  private Expression buildTree(String expr) {
    Stack s = new Stack();

    for (int i = 0; i < expr.length(); i++) {
      String currChar = expr.substring(i, i + 1);

      if (isOperator(currChar== false) {
        Expression e = new TerminalExpression(currChar);
        s.push(e);
      else {
        Expression r = (Expressions.pop();
        Expression l = (Expressions.pop();
        Expression n = getNonTerminalExpression(currChar, l, r);
        s.push(n);
      }
    }//for
    return (Expressions.pop();
  }

  private String infixToPostFix(String str) {
    Stack s = new Stack();
    String pfExpr = "";
    String tempStr = "";

    String expr = str.trim();
    for (int i = 0; i < str.length(); i++) {

      String currChar = str.substring(i, i + 1);

      if ((isOperator(currChar== false&& (!currChar.equals("("))
          && (!currChar.equals(")"))) {
        pfExpr = pfExpr + currChar;
      }
      if (currChar.equals("(")) {
        s.push(currChar);
      }
      //for ')' pop all stack contents until '('
      if (currChar.equals(")")) {
        tempStr = (Strings.pop();
        while (!tempStr.equals("(")) {
          pfExpr = pfExpr + tempStr;
          tempStr = (Strings.pop();
        }
        tempStr = "";
      }
      //if the current character is an
      // operator
      if (isOperator(currChar)) {
        if (s.isEmpty() == false) {
          tempStr = (Strings.pop();
          String strVal1 = (Stringoperators.get(tempStr);
          int val1 = new Integer(strVal1).intValue();
          String strVal2 = (Stringoperators.get(currChar);
          int val2 = new Integer(strVal2).intValue();

          while ((val1 >= val2)) {
            pfExpr = pfExpr + tempStr;
            val1 = -100;
            if (s.isEmpty() == false) {
              tempStr = (Strings.pop();
              strVal1 = (Stringoperators.get(tempStr);
              val1 = new Integer(strVal1).intValue();

            }
          }
          if ((val1 < val2&& (val1 != -100))
            s.push(tempStr);
        }
        s.push(currChar);
      }//if

    }// for
    while (s.isEmpty() == false) {
      tempStr = (Strings.pop();
      pfExpr = pfExpr + tempStr;
    }
    return pfExpr;
  }

  private boolean isOperator(String str) {
    if ((str.equals("+")) || (str.equals("-")) || (str.equals("*"))
        || (str.equals("/")))
      return true;
    return false;
  }
// End of class

class Context {
  private HashMap varList = new HashMap();

  public void assign(String var, int value) {
    varList.put(var, new Integer(value));
  }

  public int getValue(String var) {
    Integer objInt = (IntegervarList.get(var);
    return objInt.intValue();
  }

  public Context() {
    initialize();
  }

  //Values are hardcoded to keep the example simple
  private void initialize() {
    assign("a"20);
    assign("b"40);
    assign("c"30);
    assign("d"10);
  }

}

class TerminalExpression implements Expression {
  private String var;

  public TerminalExpression(String v) {
    var = v;
  }

  public int evaluate(Context c) {
    return c.getValue(var);
  }
}

interface Expression {
  public int evaluate(Context c);
}

abstract class NonTerminalExpression implements Expression {
  private Expression leftNode;

  private Expression rightNode;

  public NonTerminalExpression(Expression l, Expression r) {
    setLeftNode(l);
    setRightNode(r);
  }

  public void setLeftNode(Expression node) {
    leftNode = node;
  }

  public void setRightNode(Expression node) {
    rightNode = node;
  }

  public Expression getLeftNode() {
    return leftNode;
  }

  public Expression getRightNode() {
    return rightNode;
  }
}// NonTerminalExpression

class AddExpression extends NonTerminalExpression {
  public int evaluate(Context c) {
    return getLeftNode().evaluate(c+ getRightNode().evaluate(c);
  }

  public AddExpression(Expression l, Expression r) {
    super(l, r);
  }
}// AddExpression

class SubtractExpression extends NonTerminalExpression {
  public int evaluate(Context c) {
    return getLeftNode().evaluate(c- getRightNode().evaluate(c);
  }

  public SubtractExpression(Expression l, Expression r) {
    super(l, r);
  }
}// SubtractExpression

class MultiplyExpression extends NonTerminalExpression {
  public int evaluate(Context c) {
    return getLeftNode().evaluate(c* getRightNode().evaluate(c);
  }

  public MultiplyExpression(Expression l, Expression r) {
    super(l, r);
  }

}// MultiplyExpression


//File: Interprepter.properties
/*
a=10
b=20
c=30
d=40

*/


           
       
Related examples in the same category
1. Interpreter pattern in JavaInterpreter pattern in Java
2. Interpreter Pattern 2
w___w_w___._jav_a_2__s__.c___o_m___ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.