A very simple strategy design pattern implementation.
The repository consists of a project:
- Asp.Net Core2 Console
The calculation on 2 numbers can be made through different ways/strategy(s). Basic strategy is defined in an interface
public interface IStrategy
{
int Calculate(int x,int y);
}
- Addition calculation implementation
class Add : IStrategy
{
public int Calculate(int x, int y) { return x+y ; }
}
- Subtraction calculation implementation
class Subtract : IStrategy
{
public int Calculate(int x, int y) { return x-y ; }
}
- Multiplication calculation implementation
class Multiple : IStrategy
{
public int Calculate(int x, int y) { return x*y ; }
}
- Division calculation implementation
class Divide : IStrategy
{
public int Calculate(int x, int y) { return x/y ; }
}
- Strategy implementation
interface IStrategyCtx
{
int Perform(StrategyType type, int x, int y);
}
class StrategyCtx : IStrategyCtx
{
Dictionary<StrategyType, IStrategy> d = new Dictionary<StrategyType, IStrategy>();
public StrategyCtx()
{
d.Add(StrategyType.ADD, new Add());
d.Add(StrategyType.SUBTRACT, new Subtract());
d.Add(StrategyType.MULTIPLY, new Multiple());
d.Add(StrategyType.DIVISION, new Divide());
}
public int Perform(StrategyType type, int x, int y)
{
return d[type].Calculate(x, y);
}
}
Having any trouble? Check out our documentation or contact support and we’ll help you sort it out.