1、理解策略模式的动机,掌握该模式的结构;
2、能够利用策略模式解决实际问题。
[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
package ruanjiansheji.shiyan23;
public class AirplaneStrategy implements TravelStrategy {
@Override
public void travel() {
// TODO Auto-generated method stub
System.out.println("乘坐飞机旅游");
}
}
package ruanjiansheji.shiyan23;
public class BicycleStrategy implements TravelStrategy {
@Override
public void travel() {
// TODO Auto-generated method stub
System.out.println("自行车游");
}
}
package ruanjiansheji.shiyan23;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("我要去旅游");
Person pr=new Person();
TravelStrategy strategy=new TrainStrategy();
pr.setStrategy(strategy);
pr.travel();
}
}package ruanjiansheji.shiyan23;
public class Person {
private TravelStrategy strategy;
public void setStrategy(TravelStrategy strategy) {
this.strategy = strategy;
}
public void travel() {
strategy.travel();
}
}
package ruanjiansheji.shiyan23;
public class TrainStrategy implements TravelStrategy {
@Override
public void travel() {
// TODO Auto-generated method stub
System.out.println("乘火车旅游");
}
}
package ruanjiansheji.shiyan23;
public interface TravelStrategy {
public void travel();
}
3. 注意编程规范。