The calculator should be able to interpret the following expressions:
operator operand
operand operator operand
Examples:
3 + 5
9 – 8
sin 0
cos 0
This is the first solution that come to mind:
This is an example of a client:
and a run:
What is wrong with this code?
The strategy pattern allows you to build a more flexible system at runtime.
The strategy pattern defines a family of algorithms encapsulates each one and makes them interchangeable. The client does not need to change.
In our example is easy to recognize that the algorithms are the different operations. In reality we can recognize two different families of algorithms: unary operations and binary operations.
The new Calculator will have two list of operations that will be used in order to accomplish the task. The Calculator class does need to know nothing about the details of the algorithms.
The client of our library now have the ability to use the Calculator provided by the library implementer but in addition is now able to generate a literally infinite number of calculators even with custom and completely new operations.
Nice post. I am very thankful to you for sharing such type of information. You did a very good job in presenting the code and all the related information about the
basic calculator