[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
代码
Java
package test23;
public class AirplaneStrategy implements TravelStrategy{
@Override
public void travel() {
System.out.println("做飞机出行");
}
}
package test23;
public class BicycleStrategy implements TravelStrategy{
@Override
public void travel() {
System.out.println("自行车出游");
}
}
package test23;
public class Client {
public static void main(String[] args) {
Person person = new Person();
AirplaneStrategy airplaneStrategy = new AirplaneStrategy();
person.setStrategy(airplaneStrategy);
person.travel();
}
}
package test23;
public class Person {
private TravelStrategy strategy;
public void setStrategy(TravelStrategy strategy) {
this.strategy = strategy;
}
public void travel(){
strategy.travel();
}
}
package test23;
public class TrainStrategy implements TravelStrategy{
@Override
public void travel() {
System.out.println("火车出游");
}
}
package test23;
public interface TravelStrategy {
public void travel();
}
C++
#include <iostream>
using namespace std;
class TravelStrategy{
public:
virtual void travel(){}
};
class AirplaneStrategy: public TravelStrategy{
public:
void travel(){
cout<<"坐飞机出行"<<endl;
}
};
class BicycleStrategy: public TravelStrategy{
public:
void travel(){
cout<<"自行车出行"<<endl;
}
};
class TrainStrategy: 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(){
AirplaneStrategy strategy;
Person person;
person.setStrategy(&strategy);
person.travel();
}
标签:策略,23,travel,TravelStrategy,模式,strategy,class,void,public
From: https://www.cnblogs.com/java-six/p/16877359.html