日期:2014-05-20 浏览次数:20757 次
namespace 策略模式 { //抽象算法类 abstract class Operation { private double _leftNum; public double LeftNum { get { return _leftNum; } set { _leftNum = value; } } private double _rightNum; public double RightNum { get { return _rightNum; } set { _rightNum = value; } } public double GetResult(); } //具体算法1 继承抽象算法类 public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = LeftNum + RightNum; return result; } } public class OperationSub : Operation { public override double GetResult() { double result = 0; result = LeftNum + RightNum; return result; } } public class OperationMul : Operation { public override double GetResult() { double result = 0; result = LeftNum * RightNum; return result; } } public class OperationDiv : Operation { public override double GetResult() { double result = 0; if (LeftNum == 0) { throw new Exception("除数不能为 0。"); } result = LeftNum / RightNum; return result; } } public class OperationSqr : Operation { public override double GetResult() { double result = 0; result = LeftNum * LeftNum; return result; } } public class OperationSqrt : Operation { public override double GetResult() { double result = 0; if (LeftNum == 0) { throw new Exception("负数不能开平方根。"); } result = Math.Sqrt(LeftNum); return result; } } public class OperationReverse : Operation { public override double GetResult() { double result = 0; result = -LeftNum; return result; } } //上下文,用来维护一个对 算法 的引用 public class Context { Operation _op; public Context(Operation op) { _op = op; } public void ContextInterface() { _op.GetResult(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(CalcByBinaryOperator<int>(4, 5, (x, y) => x + y)); Console.WriteLine(CalcByBinaryOperator<float>(4.5f, 5f, (x, y) => x - y)); Console.WriteLine(CalcByBinaryOperator<double>(4f, 0.5f, (x, y) => Math.Pow(x, y))); } static T CalcByBinaryOperator<T>(T left, T right, Func<T, T, T> Strategy) { return Strategy(left, right); } } }