Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5e36401

Browse files
策略模式
策略模式
1 parent 67c209b commit 5e36401

File tree

4 files changed

+90
-0
lines changed

4 files changed

+90
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /