易学设计模式12 策略模式(Strategy)

Strategy是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类。
定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)

Strategy:策略接口,用来约束一系列具体的策略算法。Context使用这个接口来调用具体的策略实现定义的算法。
ConcreteStrategy:具体的策略实现,也就是具体的算法实现。
Context:上下文,负责和具体的策略类交互,通常上下文会持有一个真正的策略实现


[img]http://dl.iteye.com/upload/attachment/0073/4534/635bc4e3-eeeb-3c6f-b8ff-bd4fddaae6b4.jpg[/img]

应用场景:
  1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
  2、 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
  3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

[b]策略模式比较经典的例子:报价管理[/b]
对不同的客户要报不同的价格,向客户报价是非常复杂的,因此在一些CRM(客户关系管理)的系统中,会有一个单独的报价管理模块,来处理复杂的报价功能。
为了演示的简洁性,假定现在需要实现一个简化的报价管理,实现如下的功能:
(1)对普通客户或者是新客户报全价
(2)对老客户报的价格,统一折扣5%
(3)对大客户报的价格,统一折扣10%


public interface Strategy {
public double calcPrice(double goodsPrice);
}



public class NormalCustomerStrategy implements Strategy {
public double calcPrice(double goodsPrice) {
System.out.println("对于新客户或者是普通客户,没有折扣");
return goodsPrice;
}
}



public class OldCustomerStrategy implements Strategy {
public double calcPrice(double goodsPrice) {
System.out.println("对于老客户,统一折扣5%");
return goodsPrice * (1 - 0.05);
}
}



public class LargeCustomerStrategy implements Strategy {
public double calcPrice(double goodsPrice) {
System.out.println("对于大客户,统一折扣10%");
return goodsPrice * (1-0.1);
}
}



public class Price {

private Strategy strategy;

public Price(Strategy strategy) {
this.strategy = strategy;
}

public double quote(double goodsPrice) {
return strategy.calcPrice(goodsPrice);
}
}



public class Client {

public static void main(String[] args) {

Strategy strategy = new LargeCustomerStrategy ();
Price ctx = new Price(strategy);
double quote = ctx.quote(1000);
System.out.println("向客户报价:"+quote);

strategy = new OldCustomerStrategy();
ctx = new Price(strategy);
quote = ctx.quote(1000);

System.out.println("向客户报价:"+quote);
}
}


输出结果:
对于大客户,统一折扣10%
向客户报价:900.0
对于老客户,统一折扣5%
向客户报价:950.0


参考:http://blog.csdn.net/csh624366188/article/details/7470579
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值