菜鸟的博客

纵有疾风起,人生不言弃。

导航

软件设计-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();
    }
}

 

posted on 2024-11-26 15:43  hhmzd233  阅读(1)  评论(0编辑  收藏  举报