12.9日报

今天软件设计考试,晚上完成软件设计实验二十三策略模式,

实验 23:策略模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解策略模式的动机,掌握该模式的结构;

2、能够利用策略模式解决实际问题。

 
   

 

 

[实验任务一]:旅行方式的选择

旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。

实验要求:

1.  画出对应的类图;

 

2.  提交源代码;

  1. // 策略接口
    interface Strategy {
    void algorithm();
    }

    // 飞机旅行策略
    class FlyStrategy implements Strategy {
    public void algorithm() {
    System.out.println("Traveling by plane.");
    }
    }

    // 火车旅行策略
    class TrainStrategy implements Strategy {
    public void algorithm() {
    System.out.println("Traveling by train.");
    }
    }

    // 自行车旅行策略
    class BicycleStrategy implements Strategy {
    public void algorithm() {
    System.out.println("Traveling by bicycle.");
    }
    }

    // 客户端类
    class Client {
    private Strategy strategy;

    public void setStrategy(Strategy strategy) {
    this.strategy = strategy;
    }

    public void executeStrategy() {
    strategy.algorithm();
    }
    }

    // 客户端测试代码
    public class StrategyPatternTest {
    public static void main(String[] args) {
    Client client = new Client();

    System.out.println("Client: I'm not sure which algorithm to use, so I'll be ready for anything.");
    System.out.println("Client: I'll use the FlyStrategy.");
    client.setStrategy(new FlyStrategy());
    client.executeStrategy();

    System.out.println("\nClient: Now I'll use the TrainStrategy.");
    client.setStrategy(new TrainStrategy());
    client.executeStrategy();

    System.out.println("\nClient: Now I'll use the BicycleStrategy.");
    client.setStrategy(new BicycleStrategy());
    client.executeStrategy();
    }
    }

 

4.  注意编程规范。

 

 

posted @   Code13  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2023-12-13 12.13
2023-12-13 12.12
2023-12-13 12.11
2023-12-13 12.8
2023-12-13 12.7
2023-12-13 12.6
2023-12-13 12.5
点击右上角即可分享
微信分享提示