你作为一个Java领域的专家,请完成以下任务:策略模式的实现
时间: 2023-06-24 18:06:03 浏览: 39
策略模式是一种行为设计模式,它允许你定义一系列算法,把它们封装成独立的类,并且使它们可以相互替换。该模式让算法的变化独立于使用算法的客户端(使用者)。
以下是策略模式的实现:
首先,我们需要定义一个接口,该接口定义了所有具体算法类都必须实现的方法:
```
public interface Strategy {
public int doOperation(int num1, int num2);
}
```
然后,我们实现具体的算法类:
```
public class OperationAdd implements Strategy {
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class OperationSubtract implements Strategy {
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
public class OperationMultiply implements Strategy {
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
```
接着,我们定义一个上下文类,该类将使用不同的策略来执行不同的操作:
```
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
```
最后,我们可以使用上下文类来执行不同的算法:
```
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationSubtract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}
```
输出结果为:
```
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
```
这就是策略模式的实现。通过使用该模式,我们可以轻松地切换算法,而不必更改客户端代码。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)