吉吉于

free

设计模式(2):策略模式

抽象策略角色: 策略类,通常由一个接口或者抽象类实现。

具体策略角色:包装了相关的算法和行为。

环境角色:持有一个策略类的引用,最终给客户端调用。

优点:   

1、 提供了一种替代继承的方法,而且既保持了继承的优点(代码重用)还比继承更灵活(算法独立,可以任意扩展)。   

2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。   

3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。

缺点:   

1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。

Strategy.jpg

实现代码: CashSuper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Strategy
{
///
/// 现金收费类
///
</p>

 
abstract class CashSuper
{
//现金收取超类的抽象方法,收取现金,参数为原价,返回当前价
public abstract double acceptCash(double money);
}

///
/// 正常收费类,原价返回
///

 
class CashNormal : CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}

///
/// 打折收费类,初始化时,必须要输入折扣率
///

 
class CashRebate : CashSuper
{
private double moneyRebate = 1d;
public CashRebate(string moneyRebate)
{
this.moneyRebate = double.Parse(moneyRebate);
}
public override double acceptCash(double money)
{
return moneyRebate * money;
}
}

///
/// 满**返**类
///

 
class CashReturn : CashSuper
{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(string moneyCondition, string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}
public override double acceptCash(double money)
{
double result = money;
if (money >= moneyCondition)
{
result = money - Math.Floor(money/moneyCondition)*moneyReturn;
}
return result;
}
}
}

CashContext:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Strategy
{
///
/// 上下文,用一个ConcreteStrategy来配置,维护一个队Strategy对象的引用
///
</p>

 
class CashContext
{
//声明一个CashSuper对象
private CashSuper cs = null;

///
/// 初始化时,传入具体的策略对象
///

 
///
public CashContext(string type)
{
switch (type)
{
case “正常收费”:
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case “满300返100″:
CashReturn cr1 = new CashReturn(“300″,“100″);
cs = cr1;
break;
case “打8折”:
CashRebate cr2 = new CashRebate(“0.8″);
cs = cr2;
break;
}
}

///
/// 根据收费策略不同,获得计算结果
///

 
///
///
public double GetResult(double money)
{
return cs.acceptCash(money);
}

}
}

Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Strategy
{
class Program
{
static void Main(string[] args)
{
double total = 0.0d;
CashContext csuper = new CashContext(“满300返100″);
double totalPrices = 0d;
totalPrices = csuper.GetResult(1000);
Console.WriteLine(totalPrices);
}
}
}</p>

转载请注明:于哲的博客 » 设计模式(2):策略模式