设计模式—策略模式
[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
java实现
package strategy; public class Person { private TourStrategy ts; public void setTs(TourStrategy ts) { this.ts = ts; } public void travel(){ ts.travel(); } }
package strategy; public interface TourStrategy { public void travel(); }
package strategy; public class AirStrategy implements TourStrategy{ @Override public void travel() { System.out.println("乘坐飞机旅游"); } }
package strategy; public class TrainStrategy implements TourStrategy{ @Override public void travel() { System.out.println("乘坐火车旅游"); } }
package strategy; public class BikeStrategy implements TourStrategy{ @Override public void travel() { System.out.println("骑自行车旅游"); } }
package strategy; public class Client { public static void main(String[] args) { Person p = new Person(); TourStrategy air = new AirStrategy(); p.setTs(air); p.travel(); System.out.println("-------------------------"); TourStrategy train = new TrainStrategy(); p.setTs(train); p.travel(); System.out.println("-------------------------"); TourStrategy bike = new BikeStrategy(); p.setTs(bike); p.travel(); } }
c++实现
#include<iostream> using namespace std; class TourStrategy { public: virtual void travel() {}; }; class Person { private: TourStrategy *ts; public: void setTs(TourStrategy *ts) { this->ts = ts; } void travel() { ts->travel(); } }; class AirStrategy : public TourStrategy { public: void travel() { cout << "乘坐飞机旅行" << endl; } }; class TrainStrategy : public TourStrategy { public: void travel() { cout << "乘坐火车旅行" << endl; } }; class BikeStrategy : public TourStrategy { public: void travel() { cout << "骑自行车旅行" << endl; } }; int main() { Person *p = new Person(); TourStrategy *air = new AirStrategy(); p->setTs(air); p->travel(); cout << "---------------------" << endl; TourStrategy *train = new TrainStrategy(); p->setTs(train); p->travel(); cout << "---------------------" << endl; TourStrategy *bike = new BikeStrategy(); p->setTs(bike); p->travel(); return 0; }