旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
3. 注意编程规范。
1、类图
2、源代码
#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(){
cout<<"我要去旅游,选哪种出行方式呢?"<<endl;
Person *pr=new Person();
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();
}