2021.11.29
旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
(1)AirplaneStrategy.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package shiyan23; /** * @Description:具体策略类,封装算法 * @author 马荣荣 * */ public class AirplaneStrategy implements TravelStrategy{ public void travel() { System.out.println( "乘坐飞机旅行" ); } } |
(2)BicycleStrategy.java:
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
|
package shiyan23; /** * @Description:具体策略类,封装算法 * @author 马荣荣 * */ public class BicycleStrategy implements TravelStrategy{ public void travel() { System.out.println( "自行车游" ); } } |
(3)Client.java:
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
36
37
38
39
|
package shiyan23; import java.util.Scanner; public class Client { public static void main(String[] args) { Person p = new Person(); System.out.println( "请选择:1、飞机 2、火车 3、自行车" ); Scanner input= new Scanner(System.in); int i=input.nextInt(); if (i== 1 ) { p.setStrategy( new AirplaneStrategy()); } else if (i== 2 ) { p.setStrategy( new TrainStrategy()); } else if (i== 3 ) { p.setStrategy( new BicycleStrategy()); } p.travel(); } } |
(4)Person.java:
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
|
package shiyan23; /** * @Description:客户(环境类) * @author 马荣荣 * */ public class Person { //聚合策略类对象 private TravelStrategy strategy; public void setStrategy(TravelStrategy strategy) { this .strategy=strategy; } public void travel() { strategy.travel(); } } |
(5)TrainStrategy.java:
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
|
package shiyan23; /** * @Description:具体策略类,封装算法 * @author 马荣荣 * */ public class TrainStrategy implements TravelStrategy{ public void travel() { System.out.println( "乘火车旅行" ); } } |
(6)TravelStrategy.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package shiyan23; /** * @Description:抽象策略类 * @author 马荣荣 * */ public interface TravelStrategy { public void travel(); } |
实现截图: