策略模式
代码实现:
计算服务类:
namespace StrategyPattern.Service { public interface ICalculation { public int Calculate(int data1,int data2); } public class Plus:ICalculation { public int Calculate(int data1, int data2) { int ret= data1 + data2; Console.WriteLine($"{data1}+{data2}={ret}"); return ret; } } public class Subtract : ICalculation { public int Calculate(int data1, int data2) { int ret = data1 - data2; Console.WriteLine($"{data1}-{data2}={ret}"); return ret; } } public class Multiply : ICalculation { public int Calculate(int data1, int data2) { int ret = data1 * data2; Console.WriteLine($"{data1}*{data2}={ret}"); return ret; } } public class Division:ICalculation { public int Calculate(int data1, int data2) { int ret = data1 / data2; Console.WriteLine($"{data1}/{data2}={ret}"); return ret; } } }
计算上下文:
public class CalculateContext { private readonly ICalculation _calculation; private readonly int _data1; private readonly int _data2; public CalculateContext(ICalculation calculation, int data1,int data2) { _calculation = calculation; _data1 = data1; _data2 = data2; } public void DoAction() { _calculation.Calculate(_data1, _data2); } }
代码调用:
class Program { static void Main(string[] args) { int data1, data2; Console.WriteLine("整数二元运算..."); Console.WriteLine("请输入第一个整数:"); while (!int.TryParse(Console.ReadLine(), out data1)) { Console.WriteLine("请重新输入第一个整数:"); } Console.WriteLine("请选择运算符:+ - * /"); string[] ops =new string[] {"+","-","*","/"}; string op=""; op= Console.ReadLine(); while (!ops.Contains(op)) { Console.WriteLine("请重新输入运算符:+ - * / "); op = Console.ReadLine(); } Console.WriteLine("请输入第二个整数:"); while (!int.TryParse(Console.ReadLine(), out data2)) { Console.WriteLine("请重新输入第二个整数:"); } ICalculation calculation = null; if (op == "+") { calculation = new Plus(); } else if (op == "-") { calculation = new Subtract(); } else if (op == "*") { calculation = new Multiply(); } else if (op == "/") { calculation = new Division(); } CalculateContext calculateContext = new CalculateContext(calculation,data1, data2); calculateContext.DoAction(); } }