Design Calculator


  • 1
    H

    Design a Calculator using OO techniques. Extend it to Scientific calculator. What are some of the design patterns you will use?


  • 1
    V

    You can think of a calculator as an expression which contains characters like 0,1,2,...,+,-,/,*,...,sin,cos,.. The calculator evaluates this expression to return a number. One way it can evaluate an expression is to find the first thing it needs to compute, get the result, use that result to compute the next thing it needs to compute.

    Ex. "(1+2)+4", first thing you need to compute is "1" which evaluates to 1 and "2" which evaluates to 2, then you need to add them (1 + 2 = 3) and add that result to 4 (3 + 4 = 7) so the final result is 7.

    You can implement this by making an abstract class called Operation which stores some data (arg1 and arg2) and provides a method getValue() which subclasses like Literal and Add can implement. Then you can make a Calculator class which just finds the first operation it needs to calculate, calculcates it, then uses the result in the next operation, ...

    abstract class Operation:
    float arg1, arg2
    abstract float getValue()
    
    class Literal extends Operation:
    float getValue() {
    	return arg1
    }
    
    class Add extends Operation:
    float getValue() {
    	return arg1 + arg2
    }
    
    class Negate extends Operation:
    float getValue() {
    	return -arg1
    }
    
    class Calculator:
    string expression
    float evaluate()
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.