随笔 - 132  文章 - 0  评论 - 1  阅读 - 4596

实验 23:策略模式

 


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

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

实验要求:

1.  提交源代码;

package test23;

 

public class AirplaneStrategy implements TravelStrategy{

 

    public void travel() {

        System.out.println("乘坐飞机旅行");

    }

 

}

 

 

 

package test23;

public class BicycleStrategy implements TravelStrategy{

 

    public void travel() {

        System.out.println("自行车旅行");

    }

 

}

 

 

 

package test23;

 

 

import java.util.Scanner;

 

public class Client {

    public static void main(String[] args) {

        Person p = new Person();

        System.out.println("请选择:1、飞机  2、火车  3、自行车");

        Scanner input=new Scanner(System.in);

        int i=input.nextInt();

        if(i==1) {

            p.setStrategy(new AirplaneStrategy());

        }else if(i==2) {

            p.setStrategy(new TrainStrategy());

        }else if(i==3) {

            p.setStrategy(new BicycleStrategy());

        }

        p.travel();

    }

}

 

 

 

package test23;

 

 

public class Person {

    //聚合策略类对象

    private TravelStrategy strategy;

    public void setStrategy(TravelStrategy strategy) {

        this.strategy=strategy;

    }

    public void travel() {

        strategy.travel();

    }

}

 

 

 

package test23;

 

 

public class TrainStrategy implements TravelStrategy{

 

    public void travel() {

        System.out.println("乘火车旅行");

    }

 

}

 

 

 

package test23;

 

public interface TravelStrategy {

    public void travel();

}

2.注意编程规范。

 

 

posted on   wardream  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示