设计模式--体会(策略模式)
1. 策略模式
http://zh.wikipedia.org/wiki/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F
我个人觉得,策略模式是对相关算法的封装,使得算法可以自由选择和能换。比如2个数(A,B)的运算.(加减乘除).这4种运算方法对应4种不同的算法。所以我们可以把他抽象出来并封装成类。
代码
public interface ICalculate
{
double Result();
}
public class Calculate {
ICalculate _calOperate;
public Calculate(ICalculate obj)
{
this._calOperate = obj;
}
public double GetResult()
{
return this._calOperate.Result();
}
}
public class AddCalculate : ICalculate
{
private double _dbNumberA;
private double _dbNumberB;
public AddCalculate(double numA,double numB)
{
this._dbNumberA = numA;
this._dbNumberB = numB;
}
#region ICalculate Members
public double Result()
{
return this._dbNumberA + this._dbNumberB;
}
#endregion
}
{
double Result();
}
public class Calculate {
ICalculate _calOperate;
public Calculate(ICalculate obj)
{
this._calOperate = obj;
}
public double GetResult()
{
return this._calOperate.Result();
}
}
public class AddCalculate : ICalculate
{
private double _dbNumberA;
private double _dbNumberB;
public AddCalculate(double numA,double numB)
{
this._dbNumberA = numA;
this._dbNumberB = numB;
}
#region ICalculate Members
public double Result()
{
return this._dbNumberA + this._dbNumberB;
}
#endregion
}