复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.strategy; /** * 现金收取类 * @author Administrator * */ public interface CashSuper { /** * * @param money 收取现金,参数为原价,返回当前价 * @return */ public double acceptCash (double money); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package com.strategy; /** * 正常收费 ,不参加任何活动。 * @author Administrator * */ public class CashNormal implements CashSuper { @Override public double acceptCash(double money) { return money; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package com.strategy; /** * 打折收费 * @author Administrator * */ public class CashRebate implements CashSuper { private double moneyRebate = 1; public CashRebate (String rebate ){ this.moneyRebate =Double.parseDouble(rebate) ; } @Override public double acceptCash(double money) { return this.moneyRebate * money; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31package com.strategy; /** * 返利收费 ,满多少返多少 * @author Administrator * */ public class CashReturn implements CashSuper { private double moneyCondition; private double moneyReturn; public CashReturn (String moneyCondition ,String moneyReturn){ this.moneyCondition = Double.parseDouble(moneyCondition); this.moneyReturn = Double.parseDouble(moneyReturn); } @Override public double acceptCash(double money) { double result = 0 ; if (money >= this.moneyCondition){ result = money - Math.floor(money/this.moneyCondition) * this.moneyReturn; } return result; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36package com.strategy; /** * 策略 类 * @author Administrator * */ public class ContentStrategy { private CashSuper cashSuper; //初始化,传入具体策略对象 public ContentStrategy (String type){ if ("normal".equalsIgnoreCase(type)) { this.cashSuper = new CashNormal(); } else if ("rebate".equalsIgnoreCase(type)){ this.cashSuper = new CashRebate("0.8"); } else if ("return".equalsIgnoreCase(type)){ this.cashSuper = new CashReturn("300", "100"); } } //调用算法方法 public double getResult (double money){ return cashSuper.acceptCash(money); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package com.strategy; /** * 策略模式是一种定义一系列算法的方法,从概念上来看,所有的这些算法都完成相同的工作 * 只是实现不一样,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间 * 的耦合,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式 * 处理这种变化的可能性。 * @author Administrator * */ public class MainRun { public static void main(String[] args) { ContentStrategy strategy = new ContentStrategy("rebate"); double returnVal = strategy.getResult(100); System.out.println("reuturnVal = "+returnVal); } }
最后
以上就是沉静爆米花最近收集整理的关于策略模式 (商场收银软件)的全部内容,更多相关策略模式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复