12.23
实验 23:策略模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解策略模式的动机,掌握该模式的结构;
2、能够利用策略模式解决实际问题。
[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
#include<iostream>
#include<string>
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* ts;
public: Person(TravelStrategy* ts)
{
this->ts = ts;
}
void travel()
{
ts->travel();
}
};
int main() {
Person* mc;
cout << "你想选择的出行方式!" << endl;
cout << "1.飞机游" << endl;
cout << "2.火车游" << endl;
cout << "3.自行车游" << endl;
int a = 0;
cin >> a;
switch (a) {
case 1:
{TravelStrategy* at = new AirplaneStrategy();
mc = new Person(at);
mc->travel();
break;
}
case 2:
{
TravelStrategy* tr = new TrainStrategy();
mc = new Person(tr);
mc->travel();
break;
}
case 3:
TravelStrategy * by = new BicycleStrategy();
mc = new Person(by);
mc->travel();
}
//Person mc=new Person((TravelStrategy)XMLUtil.getBean());
}
3. 注意编程规范。
浙公网安备 33010602011771号