[實驗任務一]:旅行方式的選擇
旅遊的出行方式有乘坐飛機旅行、乘火車旅行和腳踏車遊,不同的旅遊方式有不同的實現過程,客戶可以根據自己的需要選擇一種合適的旅行方式。
實驗要求:
1. 畫出對應的類圖;
2. 提交原始碼;
package strategy;
public class Person {
private TourStrategy ts;
public void setTs(TourStrategy ts) {
this.ts = ts;
}
public void travel(){
ts.travel();
}
}
package strategy;
public interface TourStrategy {
public void travel();
}
package strategy;
public class AirStrategy implements TourStrategy{
@Override
public void travel() {
System.out.println("乘坐飛機旅遊");
}
}
package strategy;
public class TrainStrategy implements TourStrategy{
@Override
public void travel() {
System.out.println("乘坐火車旅遊");
}
}
package strategy;
public class BikeStrategy implements TourStrategy{
@Override
public void travel() {
System.out.println("騎腳踏車旅遊");
}
}
package strategy;
public class Client {
public static void main(String[] args) {
Person p = new Person();
TourStrategy air = new AirStrategy();
p.setTs(air);
p.travel();
System.out.println("-------------------------");
TourStrategy train = new TrainStrategy();
p.setTs(train);
p.travel();
System.out.println("-------------------------");
TourStrategy bike = new BikeStrategy();
p.setTs(bike);
p.travel();
}
}
3. 注意程式設計規範。