策略测试代码
时间: 2023-07-13 14:13:07 浏览: 42
好的,以下是一个简单的策略模式的测试代码示例:
```java
// 策略接口
interface Strategy {
void execute();
}
// 具体策略类A
class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("执行策略A");
}
}
// 具体策略类B
class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("执行策略B");
}
}
// 策略上下文
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
// 测试代码
public class StrategyTest {
public static void main(String[] args) {
Context context = new Context(new ConcreteStrategyA()); // 初始化时设置策略A
context.executeStrategy(); // 执行策略A
context.setStrategy(new ConcreteStrategyB()); // 设置策略B
context.executeStrategy(); // 执行策略B
}
}
```
在以上代码中,策略接口`Strategy`定义了策略的执行方法`execute()`,并由具体的策略类实现。策略上下文`Context`包含一个策略对象,通过`setStrategy()`方法可以动态设置不同的策略对象,`executeStrategy()`方法则执行当前策略对象的`execute()`方法。在测试代码中,我们创建了一个`Context`对象,并将其初始化时设置为具体策略类A的实例,执行`executeStrategy()`方法后会输出“执行策略A”,然后将其策略对象设置为具体策略类B的实例,再次执行`executeStrategy()`方法会输出“执行策略B”。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)