File tree Expand file tree Collapse file tree 4 files changed +90
-0
lines changed
java-des/src/com/java/design/strategy Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .java .design .strategy ;
2
+
3
+ /**
4
+ * 计算接口
5
+ *
6
+ * @author Administrator
7
+ *
8
+ */
9
+ public interface CalculateStrategy {
10
+
11
+ void calculatePrice (Integer km );
12
+
13
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .strategy ;
2
+
3
+ /**
4
+ * 公交计算策略
5
+ *
6
+ * @author Administrator
7
+ *
8
+ */
9
+ public class Strategy implements CalculateStrategy {
10
+
11
+ private String name ;
12
+
13
+ public Strategy (String name ) {
14
+ this .name = name ;
15
+ }
16
+
17
+ @ Override
18
+ public void calculatePrice (Integer km ) {
19
+
20
+ Integer priceTot = 0 ;
21
+
22
+ if (name == "公交" ) {
23
+ int extraTotal = km - 10 ;
24
+ int extraFactor = extraTotal / 5 ;
25
+ int fraction = extraTotal % 5 ;
26
+ int price = 1 + extraFactor * 1 ;
27
+ priceTot = fraction > 0 ? ++price : price ;
28
+ } else if (name == "地铁" ) {
29
+ if (km <= 6 ) {
30
+ priceTot = 3 ;
31
+ } else if (km > 6 && km < 12 ) {
32
+ priceTot = 4 ;
33
+ } else if (km < 22 && km > 12 ) {
34
+ priceTot = 5 ;
35
+ } else if (km < 32 && km > 22 ) {
36
+ priceTot = 6 ;
37
+ } else {
38
+ priceTot = 7 ;
39
+ }
40
+ }
41
+ System .out .println (name + "坐" + km + "公里需要" + priceTot + "元 ..." );
42
+ }
43
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .strategy ;
2
+
3
+ /**
4
+ * 策略模式 -----> 策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。
5
+ * 策略模式使得算法可以在不影响到客户端的情况下发生变化
6
+ *
7
+ * @author Administrator
8
+ *
9
+ */
10
+ public class StrategyPattern {
11
+
12
+ public static void main (String [] args ) {
13
+
14
+ TranficCalculator tranficCalculator = new TranficCalculator ();
15
+ // 设置计算策略
16
+ // 计算价格
17
+ tranficCalculator .calculatePrice (new Strategy ("地铁" ), 10 );
18
+
19
+ }
20
+
21
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .strategy ;
2
+
3
+ public class TranficCalculator {
4
+
5
+ CalculateStrategy calculateStrategy ;
6
+
7
+ public void calculatePrice (CalculateStrategy calculateStrategy , Integer km ) {
8
+
9
+ this .calculateStrategy = calculateStrategy ;
10
+ calculateStrategy .calculatePrice (km );
11
+ }
12
+
13
+ }
You can’t perform that action at this time.
0 commit comments