Strategy

1 //策略类,定义所有支持的算法的公共接口
2 public abstract class CashStrategy
3 {
4 public abstract double algorithmInterface(double money);
5 }
 1 //具体策略,封装具体的算法或行为,继承Stragtegy
2 public class CashRebate extends CashStrategy
3 {
4 private double moneyRebate;
5
6 public CashRebate(double rebate)
7 {
8 this.moneyRebate = rebate;
9 }
10
11 @Override
12 public double algorithmInterface(double money)
13 {
14 return money * moneyRebate;
15 }
16
17 }
1 public class CashNomal extends CashStrategy
2 {
3 @Override
4 public double algorithmInterface(double money)
5 {
6 return money;
7 }
8 }
 1 public class CashReturn extends CashStrategy
2 {
3 private double moneyCondition;
4 private double moneyReturn;
5
6 public CashReturn(double moneyCondition, double moneyReturn)
7 {
8 this.moneyCondition = moneyCondition;
9 this.moneyReturn = moneyReturn;
10 }
11
12 @Override
13 public double algorithmInterface(double money)
14 {
15 return money - ((int)(money / moneyCondition))*moneyReturn;
16 }
17 }
 1 //Context上下文,维护对Strategy对象的引用。
2 public class CashContext
3 {
4 private CashStrategy strategy;
5
6 //与简单工厂结合
7 public CashContext(String type)
8 {
9 if ("正常消费".equals(type))
10 {
11 strategy = new CashNomal();
12 }
13 else if ("打八折".equals(type))
14 {
15 strategy = new CashRebate(0.8);
16 }
17 else if ("满300返100".equals(type))
18 {
19 strategy = new CashReturn(300, 100);
20 }
21 }
22
23 public double getResult(double money)
24 {
25 //根据收费策略不同,获得计算结果。
26 return strategy.algorithmInterface(money);
27 }
28 }
1  public static void main(String[] args)
2 {
3 CashContext context = new CashContext("打八折");
4 System.out.println(context.getResult(100));
5 }

策略模式:它定义了算法家族,分别封装起来,让它们之前相互替换,此模式让算法的运算,不会影响到使用算法的用户。

策略模式的Strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于析取出这些算法的公共功能。(例子中的打折,返利,或者其它算法,都是对实际商品收费的的一种计算方式)

策略模式是用来封装算法,但实践中,它可以封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不用的业务规则,就可以考虑策略模式处理这种变化的可能性。

在基本的策略模式中,选择所具体实现的职能由客户端对象承担,并转给策略模式的Context对象。

  

原文地址:https://www.cnblogs.com/xuekyo/p/2389276.html