1 package com.calipso.reportgenerator.reportcalculator.arithmetic; 2 3 import com.calipso.reportgenerator.reportcalculator.arithmetic.ArithmeticExpression; 4 5 import java.util.Map ; 6 import java.util.HashMap ; 7 import java.util.Collection ; 8 import java.io.Serializable ; 9 10 13 14 public class OperationArithmeticExp extends ArithmeticExpression implements Serializable { 15 private ArithmeticExpression m1; 16 private ArithmeticExpression m2; 17 private String operator; 18 private static Map operations; 19 20 26 private Operation fromOperator(String operator) { 27 if (operations == null){ 28 operations = new HashMap (); 29 operations.put("+", new Addition()); 30 operations.put("-", new Substraction()); 31 operations.put("*", new Multiplication()); 32 operations.put("/", new Divission()); 33 } 34 return (Operation) operations.get(operator); 35 } 36 37 42 public float value(Map context) { 43 return fromOperator(operator).calculate(m1.value(context), m2.value(context)); 44 } 45 46 50 public String toString() { 51 String str = m1.toString() + " " + operator + " " + m2.toString(); 52 if (operator.equals("+") || operator.equals("-")) { 53 return "(" + str + ")"; 54 } 55 return str; 56 } 57 58 66 public static ArithmeticExpression newOperationFrom(ArithmeticExpression subExp1, String operator, ArithmeticExpression subExp2) { 67 return new OperationArithmeticExp(subExp1, operator, subExp2); 68 } 69 70 76 public OperationArithmeticExp(ArithmeticExpression subExp1, String operator, ArithmeticExpression subExp2) { 77 this.m1 = subExp1; 78 this.m2 = subExp2; 79 this.operator = operator; 80 } 81 82 86 private abstract class Operation { 87 public abstract float calculate(float value1, float value2); 88 } 89 90 93 private class Addition extends Operation { 94 public float calculate(float value1, float value2){ 95 return value1 + value2; 96 } 97 } 98 99 102 private class Substraction extends Operation { 103 public float calculate(float value1, float value2){ 104 return value1 - value2; 105 } 106 } 107 108 111 private class Multiplication extends Operation { 112 public float calculate(float value1, float value2){ 113 return value1 * value2; 114 } 115 } 116 117 120 private class Divission extends Operation { 121 public float calculate(float value1, float value2){ 122 return value1 / value2; 123 } 124 } 125 126 public void getVariables(Collection variables) { 127 m1.getVariables(variables); 128 m2.getVariables(variables); 129 } 130 131 } | Popular Tags |