您的位置:首页 > 其它

笔记-大话设计模式-02 策略模式

2015-09-08 15:34 253 查看
面向对象编程并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类。

策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响使用算法的客户。

策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。

Strategy的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试;每个算法可保证它没有错误,修改其中任一个时不会影响其他算法。
当不同的行为堆砌在一个类中时,就很难避免使用条件语句来选择合适的行为。将这些行为封装在一个个独立的Strategy类中,可以在使用这些行为的类中消除条件语句。

Strategy就是用来封装算法的。

策略模式的基本代码:

abstract class Strategy
{
public abstract void Algorithm();
}


class AStrategy : Strategy
{
public override void Algorithm()
{
Console.WriteLine("具体算法A的实现");
}
}


class BStrategy : Strategy
{
public override void Algorithm()
{
Console.WriteLine("具体算法B的实现");
}
}


class Context
{
private Strategy strategy;
public Context(Strategy strategy)
{
this.strategy = strategy;
}

public void CreateStrategy()
{
strategy.Algorithm();
}

}


应用层:

Context context;

context = new Context(new AStrategy());
context.CreateStrategy();

context = new Context(new BStrategy());
context.CreateStrategy();


再看一个代码例子:

abstract class Charge
{
public abstract double DoCharge(double money);
}


class DiscountCharge : Charge
{
private double discountRate = 1d;
public DiscountCharge(double discountRate)
{
this.discountRate = discountRate;
}

public override double DoCharge(double money)
{
return money * discountRate;
}
}


class NormalCharge : Charge
{
public override double DoCharge(double money)
{
return money;
}
}


class ChargeContext
{
Charge charge = null;

public ChargeContext(int type)
{
switch (type)
{
case 0:
charge = new NormalCharge();
break;
case 1:
charge = new DiscountCharge(0.8d);
break;
case 2:
charge = new RebateCharge(300d, 100d);
break;
default:
throw new NotImplementedException("未实现的算法");
}
}

public double GetChargeResult(double money)
{
return charge.DoCharge(money);
}
}


应用层:

ChargeContext cc = new ChargeContext(2);

Console.WriteLine(cc.GetChargeResult(700d));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: