// This implements Interfaces which are stored in the "Code" folder referenced above static void UseInterfaces() { string add = "+"; string subtract = "-"; string multiply = "*"; string divide = "/"; var numOne = 2; var numTwo = 3; string userChoice = add; Dictionary <string, IMathOperator> strategies = new Dictionary <string, IMathOperator>() { { "+", new MathAdd() }, { "-", new MathSubtract() }, { "*", new MathMultiply() }, { "/", new MathDivide() } }; IMathOperator selectedStrategy = strategies[userChoice]; int result = selectedStrategy.Operation(numOne, numTwo); Console.WriteLine(result); }
static void FancyDict(int numOne, int numTwo, string userChoice, double result) { // Even Better: Return functions to avoid expensive instantiating Dictionary <string, Func <IMathOperator> > strategies = new Dictionary <string, Func <IMathOperator> >() { { "+", () => new MathAdd() }, { "-", () => new MathMinus() }, { "*", () => new MathMultiply() }, { "/", () => new MathDivide() } }; IMathOperator selectedStrategy = strategies[userChoice](); result = selectedStrategy.Operation(numOne, numTwo); Console.WriteLine(result); }
static void Dict(int numOne, int numTwo, string userChoice, double result) { // Better: Dictionary with interface Dictionary <string, IMathOperator> strategies = new Dictionary <string, IMathOperator>() { { "+", new MathAdd() }, { "-", new MathMinus() }, { "*", new MathMultiply() }, { "/", new MathDivide() } }; IMathOperator selectedStrategy = strategies[userChoice]; result = selectedStrategy.Operation(numOne, numTwo); Console.WriteLine(result); }