Monday 10 September 2012

Strategy Pattern - Basic Calculator

Let's say we want to implement a simple calculator that is able to calculate a single expression using unary and binary operators.

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?

I would say nothing considering the simplicity of the example. 

However, if you think a little bit you realize that this solution is not quite flexible as a client perspective. The client can use this Calculator class with a set of built in operations and he has no way to change this both at compile time and at run time. In order to support a new operation the library owner can simply add a new case statement, the client will be able to use the new operation but not to add new one at runtime. The Calculator will always have a fixed set of operations like implemented by his creator.

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.

This is an example of how to create a calculator with the additional power operation with a syntax like in Python.






1 comment:

  1. 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

    ReplyDelete

What you think about this post? I really appreciate your constructive feedback (positive and negative) and I am looking forward to start a discussion with you on this topic.