12.9日报
今天软件设计考试,晚上完成软件设计实验二十三策略模式,
实验 23:策略模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解策略模式的动机,掌握该模式的结构;
2、能够利用策略模式解决实际问题。
[实验任务一]:旅行方式的选择
旅游的出行方式有乘坐飞机旅行、乘火车旅行和自行车游,不同的旅游方式有不同的实现过程,客户可以根据自己的需要选择一种合适的旅行方式。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
- // 策略接口
interface Strategy {
void algorithm();
}
// 飞机旅行策略
class FlyStrategy implements Strategy {
public void algorithm() {
System.out.println("Traveling by plane.");
}
}
// 火车旅行策略
class TrainStrategy implements Strategy {
public void algorithm() {
System.out.println("Traveling by train.");
}
}
// 自行车旅行策略
class BicycleStrategy implements Strategy {
public void algorithm() {
System.out.println("Traveling by bicycle.");
}
}
// 客户端类
class Client {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.algorithm();
}
}
// 客户端测试代码
public class StrategyPatternTest {
public static void main(String[] args) {
Client client = new Client();
System.out.println("Client: I'm not sure which algorithm to use, so I'll be ready for anything.");
System.out.println("Client: I'll use the FlyStrategy.");
client.setStrategy(new FlyStrategy());
client.executeStrategy();
System.out.println("\nClient: Now I'll use the TrainStrategy.");
client.setStrategy(new TrainStrategy());
client.executeStrategy();
System.out.println("\nClient: Now I'll use the BicycleStrategy.");
client.setStrategy(new BicycleStrategy());
client.executeStrategy();
}
}
4. 注意编程规范。