策略设计模式
s
/// <summary>
/// 收入算法的基本结构
/// </summary>
public interface Income
{
double TotalCount();
}
/// <summary>
/// 一种收入算法
/// </summary>
public class FirstLevelIncome:Income
{
private double p;
private int total;
public FirstLevelIncome(double p, int total)
{
this.p = p;
this.total = total;
}
#region Income Members
public double TotalCount()
{
return total * p;
}
#endregion
}
/// <summary>
/// 客户需要的上下文
/// </summary>
public class CashContext
{
public Income GetStrategy(int type)
{
switch (type)
{
case 300:
Income income = new FirstLevelIncome(0.8, type);
return income;
}
return null;
}
}
public class TestIncome
{
public static void Run()
{
int total = 300;
double realTotal=0;
//此处根据收入的不同,可以得到不同的算法。
//它感觉不到算法的变化
Income myIncome = new CashContext().GetStrategy(total);
realTotal = myIncome.TotalCount();
Console.WriteLine(realTotal.ToString());
}
}
策略设计模式:
他把各种算法封装起来,他们之间可以相互替换,当算法发生变化的时候,不会影响使用它的客户。

浙公网安备 33010602011771号