With the strategy pattern it is possible to change or extend the behaviour of a Class.
This sounds a bit abstract, but let's look at an example.
public interface IMathOperation
{
double PerformOperation(double A, double B);
}
class DoMath
{
private double _A;
private double _B;
public DoMath(double A, double B)
{
_A = A;
_B = B;
}
public double DoMathOperation(IMathOperation operation)
{
return operation.PerformOperation(_A, _B);
}
}
The DoMath Class, simple as it may be, makes use of the IMathOperation. Now just assume that DoMath does a lot more than what it does now, but somewhere it needs to do that math operation. By passing an IMathOperation you can tell the DoMath Class that it should perform an Add or Substraction. If you would have used the statis Class this would not have been possible. Your DoMathOperation would have looked something like:
public double DoMathOperation()
{
return SimpleMathOperations.Add(_A, _B);
}
Now all this Class will ever do is Add. If the behaviour needs to change you need to break open and change your Class, which is not what you want.
Another gain you will get from the Strategy Pattern is that when, should the need arise, you can easily create new MathOperations. You now have Add, Subtract, Divide and Multiply, but maybe you'll get a NthRoot operation one day. You could easily create a new Class, Implement IMathOperation and write code for A^B (or however that looks in code...). If you now pass your new Class to the DoMathOperation Function you have changed the behaviour of the DoMath Class without having to change it.
The idea that a Class is closed for modification (you'll never have to change anything in the DoMath Class), but open for extension (you can write new IMathOperations and pass it as parameter to DoMathOperation) is called the Open-Closed Principle or OCP, one of the SOLID principles of Object Oriented Programming. More on SOLID principles
here[
^] and more on OCP in specific
here[
^].
Of course you do not need the Strategy Pattern if adding, subtracting, multiplying or dividing is the only thing that makes sense in a certain scenario. If, for example, you need to calculate the total sum of money on an order with 5 items which each cost $10 you would always use 5 * 10 or:
double total = SimpleMathOperation.Multiply(orderedAmount, price);
I hope that was a bit understandable :)