旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
//Person.java package test23; public class Person { //聚合策略类对象 private TravelStrategy strategy; public void setStrategy(TravelStrategy strategy) { this.strategy=strategy; } public void travel() { strategy.travel(); } } //TravelStrategy.java package test23; public interface TravelStrategy { public void travel(); } //AirplaneStrategy.java package test23; public class AirplaneStrategy implements TravelStrategy{ public void travel() { System.out.println("乘坐飞机旅行"); } } //BicycleStrategy.java package test23; public class BicycleStrategy implements TravelStrategy{ public void travel() { System.out.println("自行车游"); } } //TrainStrategy.java package test23; public class TrainStrategy implements TravelStrategy{ public void travel() { System.out.println("乘火车旅行"); } } //Client.java 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(); } }
标签:java,策略,test23,travel,TravelStrategy,模式,void,public From: https://www.cnblogs.com/qiuyutingyyds/p/17001593.html