策略模式

发布时间 2023-12-18 10:38:13作者: YE-

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

1. 提交源代码;

2.	#include<iostream>
3.	using namespace std;
4.	class TravelStrategy {
5.	public:
6.	    virtual void travel()=0;
7.	};
8.	class Person {
9.	private:
10.	    TravelStrategy *strategy;
11.	public:
12.	    void setStrategy(TravelStrategy *strategy) {
13.	        this->strategy=strategy;
14.	    }
15.	    void travel() {
16.	        this->strategy->travel();
17.	    }
18.	};
19.	class TrainStrategy : public TravelStrategy{
20.	public:
21.	    void travel() {
22.	        cout<<"乘火车旅游"<<endl;
23.	    }
24.	};
25.	class BicycleStrategy : public TravelStrategy{
26.	public:
27.	    void travel() {
28.	        cout<<"自行车游"<<endl;
29.	    }
30.	};
31.	class AirplaneStrategy: public TravelStrategy{
32.	public:
33.	    void travel() {
34.	        cout<<"乘坐飞机旅游"<<endl;
35.	    }
36.	};
37.	int main(){
38.	        cout<<"请选择旅游方式"<<endl;
39.	        Person *pr=new Person();
40.	        TravelStrategy *strategy=new TrainStrategy();
41.	        pr->setStrategy(strategy);
42.	        pr->travel();
43.	        cout<<"------------------------------"<<endl;
44.	        cout<<"请选择旅游方式"<<endl;
45.	        TravelStrategy *strategy2=new BicycleStrategy();
46.	        pr->setStrategy(strategy2);
47.	        pr->travel();
48.	        cout<<"------------------------------"<<endl;
49.	        cout<<"请选择旅游方式"<<endl;
50.	        TravelStrategy *strategy3=new AirplaneStrategy();
51.	        pr->setStrategy(strategy3);
52.	        pr->travel();
53.	}