旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
类图
Java
package rjsj.no23; public class BicycleStrategy implements TravelStrategy{ @Override public void travel() { System.out.println("骑自行车旅游"); } }
package rjsj.no23; public class Client { public static void main(String[] args) { Traveler traveler = new Traveler(); System.out.println("旅游开始!"); TravelStrategy travelStrategy = new TrainStrategy(); traveler.setTravelStrategy(travelStrategy); traveler.travel(); System.out.println("**************************************************"); System.out.println("旅游开始!"); travelStrategy = new AirplaneStrategy(); traveler.setTravelStrategy(travelStrategy); traveler.travel(); System.out.println("**************************************************"); System.out.println("旅游开始!"); travelStrategy = new BicycleStrategy(); traveler.setTravelStrategy(travelStrategy); traveler.travel(); System.out.println("**************************************************"); } }
package rjsj.no23; public class TrainStrategy implements TravelStrategy{ @Override public void travel() { System.out.println("坐火车旅游"); } }
package rjsj.no23; public class Traveler { private TravelStrategy travelStrategy; public void setTravelStrategy(TravelStrategy travelStrategy) { this.travelStrategy = travelStrategy; } public void travel(){ travelStrategy.travel(); } }
package rjsj.no23; public interface TravelStrategy { void travel(); }
package rjsj.no23; public class AirplaneStrategy implements TravelStrategy{ @Override public void travel() { System.out.println("乘坐飞机旅游"); } }
C++
#include<iostream> using namespace std; class TravelStrategy { public: virtual void travel()=0; }; class Person { private: TravelStrategy *strategy; public: void setStrategy(TravelStrategy *strategy) { this->strategy=strategy; } void travel() { this->strategy->travel(); } }; class TrainStrategy : public TravelStrategy{ public: void travel() { cout<<"坐火车"<<endl; } }; class BicycleStrategy : public TravelStrategy{ public: void travel() { cout<<"骑自行车"<<endl; } }; class AirplaneStrategy: public TravelStrategy{ public: void travel() { cout<<"坐飞机"<<endl; } }; int main(){ Person *pr=new Person(); cout<<"旅游开始,请选择交通工具:"<<endl; TravelStrategy *strategy=new TrainStrategy(); pr->setStrategy(strategy); pr->travel(); cout<<"****************************************"<<endl; cout<<"旅游开始,请选择交通工具:"<<endl; TravelStrategy *strategy2=new BicycleStrategy(); pr->setStrategy(strategy2); pr->travel(); cout<<"****************************************"<<endl; cout<<"旅游开始,请选择交通工具:"<<endl; TravelStrategy *strategy3=new AirplaneStrategy(); pr->setStrategy(strategy3); pr->travel(); }
运行结果:
标签:System,策略,travel,TravelStrategy,模式,travelStrategy,void,public From: https://www.cnblogs.com/libin159/p/16854753.html