I have to write a class in Java that supports representing arithmetic expressions with 2 methods- eval and toString with the following black-box use:
Expression e =
new Multiplication(
new Addition(
new Double(2.5),
new Double(3.5)),
new UnaryMinus(
new Integer(5)));
System.out.println(e.eval()); // should print out -30.0
System.out.println(e.toString()); // should print out ((2.5 + 3.5) * (-(5)))
How can I design such class? Which tools? Which Design pattern?
You just need to implement each operator’s
toStringandevalappropriately. Then, have each calltoStringorevalon each of their components as needed, before applying their own part.So
Addition.eval()will performreturn left.eval() + right.eval();Similarly,
Addition.toString()will performreturn "(" + left.toString() + " + " + right.toString() + ")";In order to achieve this, you’d use an interface with the Composite pattern Rob suggested to build appropriate classes overriding these methods.