Tuesday, November 12, 2013

Strategy Design Pattern

Hello

There is pretty simple pattern, which make encapsulation of algorithms

Class diagrams, from different points of view.

Class Diagram

Fig 1:class diagram without associations

Fig 2: class diagram with client associations

Fig 3: class diagram with associations inside of Startegy pattern

Explanations of class diagrams from point of view of Associations:
Fig 1: Nothing to say
Fig 2: Client should know only Context class because of client instantiate it. Client should know about all implemented algorithms, because of client instantiate context with specific algorithm.
Fig 3: Inside of pattern implementation, only Context should know about IStrategy, because of Contexts instantiated with IStrategy interface.

Code is example of calculations algorithms:

namespace StrategyDP
{
    public class Calculator
    {
        private ICalculation _calc;

        public Calculator(ICalculation calc)
        {
            _calc = calc;
        }

        public double Calculate(double a, double b)
        {
            return _calc.Calculate(a, b);
        }
    }

    public interface ICalculation
    {
        double Calculate(double a, double b);
    }

    public class AddAlg : ICalculation
    {
        public double Calculate(double a, double b)
        {
            return a + b;
        }
    }

    public class MinusAlg : ICalculation
    {
        public double Calculate(double a, double b)
        {
            return a - b;
        }
    }

    public class DevAlg : ICalculation
    {
        public double Calculate(double a, double b)
        {
            return a / b;
        }
    }

    public class MulAlg : ICalculation
    {
        public double Calculate(double a, double b)
        {
            return a * b;
        }
    }
}

Using (as UniTest):
Calculator calc = new Calculator(new AddAlg());
Assert.AreEqual(calc.Calculate(6, 2), 8);
calc = new Calculator(new MinusAlg());
Assert.AreEqual(calc.Calculate(6, 2), 4);
calc = new Calculator(new DevAlg());
Assert.AreEqual(calc.Calculate(6, 2), 3);
calc = new Calculator(new MulAlg());
Assert.AreEqual(calc.Calculate(6, 2), 12);

That's all

No comments:

Post a Comment