每日博客

策略模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解策略模式的动机,掌握该模式的结构;

2、能够利用策略模式解决实际问题。

 

 

[实验任务一]:旅行方式的选择

旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。

C++版

#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();
}
return 0;
}

posted @ 2021-11-06 21:02  谦寻  阅读(53)  评论(0编辑  收藏  举报