java策略模式示例代码
时间: 2023-12-06 22:38:45 浏览: 84
java策略模式示例.zip
以下是Java中策略模式的示例代码:
首先,我们定义一个策略接口`Strategy`,其中包含一个方法`doOperation`:
```java
public interface Strategy {
int doOperation(int num1, int num2);
}
```
然后,我们实现两个具体的策略类`OperationAdd`和`OperationSubtract`,分别实现了`Strategy`接口中的`doOperation`方法:
```java
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class OperationSubtract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
```
接下来,我们定义一个`Context`类,它包含一个`Strategy`接口类型的成员变量`strategy`,并提供了一个`executeStrategy`方法,用于执行具体的策略:
```java
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);
}
}
```
最后,我们可以使用`Context`类来执行具体的策略:
```java
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));
}
}
```
输出结果为:
```
10 + 5 = 15
10 - 5 = 5
```
阅读全文