软件设计实验23
实验 23:策略模式
[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
#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();
}
浙公网安备 33010602011771号