#include<iostream> using namespace std; class TravelStrategy{ public: virtual void travel()=0; }; class AirplaneStrategy:public TravelStrategy{ public: void travel(){ cout<<"乘坐飞机旅行"<<endl; } }; class TrainStrategy:public TravelStrategy{ public: void travel(){ cout<<"乘坐火车旅行"<<endl; } }; class BicycleStrategy:public TravelStrategy{ public: void travel(){ cout<<"骑自行车旅行"<<endl; } }; class Person{ private: TravelStrategy *strategy; public: void setStrategy(TravelStrategy *strategy){ this->strategy=strategy; } void travel(){ strategy->travel(); } }; //测试函数 int main(){ Person *p=new Person(); TravelStrategy *travel; cout<<"出行方式:"<<endl; cout<<" 1.飞机\n 2.火车\n 3.自行车"<<endl; cout<<"-------------------------------------"<<endl; cout<<"请选择您的旅游方式:"<<endl; int i; cin>>i; if(i==1){ travel=new AirplaneStrategy(); }else if(i==2){ travel=new TrainStrategy(); }else if(i==3){ travel=new BicycleStrategy(); }else{ cout<<"输入有误!"<<endl; } p->setStrategy(travel); p->travel(); }
标签:策略,travel,TravelStrategy,模式,else,void,new,public From: https://www.cnblogs.com/qiuyutingyyds/p/17001597.html