标签:
策略模式适用用,解决同一个问题,有不同的方法(策略),我们可以根据配置环境或者参数的不同选择一种策略去处理。
计算器的策略代码:
两个输入数:
输入数1,
输入数2,
这两个数可以做N种计算(+-*/.......),根据输入的运算符不同,选择不同的策略模式。
代码:
运算符抽像:
public abstract class BaseOperation { public int LeftInput { get; set; } public int RightInput { get; set; } public abstract int Compute(); }
上下文环境:
public class Context { private BaseOperation baseOperation = null; public Context(BaseOperation baseoperation) { baseOperation = baseoperation; } public int Compute(int LeftInput, int RightInput) { baseOperation.LeftInput = LeftInput; baseOperation.RightInput = RightInput; return baseOperation.Compute(); } }
运算符:
public class Plus : BaseOperation { public override int Compute() { return LeftInput + RightInput; } } public class Minus : BaseOperation { public override int Compute() { return LeftInput - RightInput; } } public class Multiply : BaseOperation { public override int Compute() { return LeftInput * RightInput; } } public class Divide : BaseOperation { public override int Compute() { return LeftInput / RightInput; } }
简单工厂:
public class SimpleFactory { /// <summary> /// 用枚举来创建的方法,仍然有耦合,使用端必须知道引用哪个子类 /// </summary> /// <param name="heroType"></param> /// <returns></returns> public static BaseOperation GetInstance(string OperationString) { switch (OperationString) { case "+": return new Plus(); case "-": return new Minus(); case "*": return new Multiply(); case "/": return new Divide(); default: throw new Exception("输入错误"); } } }
使用:
while (true) { Console.WriteLine("请输入左边数"); int LeftInput = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入运算符:+ - * /"); string OperationString = Console.ReadLine(); Console.WriteLine("请输入右边数"); int RightInput = Convert.ToInt32(Console.ReadLine()); ///上端不知道,创建、选择,依赖。上端是稳定的 Context context = new Context(SimpleFactory.GetInstance(OperationString)); Console.WriteLine("{0}{1}{2}={3}", LeftInput, OperationString, RightInput, context.Compute(LeftInput, RightInput)); }
运行结果图:
标签:
原文地址:http://www.cnblogs.com/lystory/p/5700180.html