软件设计-Tutorial23
类图:
classDiagram class TravelContext { - TravelStrategy strategy + setTravelStrategy(TravelStrategy) + executeTravel() } class TravelStrategy { <<interface>> + travel() } class AirplaneTravel { + travel() } class TrainTravel { + travel() } class BicycleTravel { + travel() } TravelContext --> TravelStrategy TravelStrategy <|.. AirplaneTravel TravelStrategy <|.. TrainTravel TravelStrategy <|.. BicycleTravel
源码
// TravelStrategy.java public interface TravelStrategy { void travel(); } // AirplaneTravel.java public class AirplaneTravel implements TravelStrategy { @Override public void travel() { System.out.println("乘坐飞机旅行,速度最快,但费用较高。"); } } // TrainTravel.java public class TrainTravel implements TravelStrategy { @Override public void travel() { System.out.println("乘坐火车旅行,舒适且性价比高。"); } } // BicycleTravel.java public class BicycleTravel implements TravelStrategy { @Override public void travel() { System.out.println("骑自行车旅行,环保且自由,但适合短途旅行。"); } } // TravelContext.java public class TravelContext { private TravelStrategy strategy; public void setTravelStrategy(TravelStrategy strategy) { this.strategy = strategy; } public void executeTravel() { if (strategy == null) { System.out.println("请选择一种旅行方式!"); } else { strategy.travel(); } } } // Main.java public class Main { public static void main(String[] args) { TravelContext context = new TravelContext(); System.out.println("=== 选择飞机旅行 ==="); context.setTravelStrategy(new AirplaneTravel()); context.executeTravel(); System.out.println("\n=== 选择火车旅行 ==="); context.setTravelStrategy(new TrainTravel()); context.executeTravel(); System.out.println("\n=== 选择自行车旅行 ==="); context.setTravelStrategy(new BicycleTravel()); context.executeTravel(); } }