Strategy Design Pattern - Basic Calculator
Andrea Angella
Technical Lead @ Redgate Software | ?Former Six-Times MVP on C# | ?? Grow Software Engineering Leaders | ?? Trainer, Mentor and Coach @ productivecsharp.com | ?? Host of The Productive C# Podcast | ?? Books Reader
This post was originally written on the Productive C# blog in 2012.
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.