用Java写策略模式的一段demo
时间: 2023-03-24 19:02:53 浏览: 79
《设计模式与游戏完美开发》java demo.zip
好的,我可以回答这个问题。以下是用Java写策略模式的一段demo:
首先,我们需要定义一个策略接口,例如:
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;
}
}
最后,我们可以定义一个Context类,用于执行不同的策略,例如:
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类来执行不同的策略了,例如:
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
Context context = new Context(new OperationSubtract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
Context context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
希望这个demo能够帮助你理解策略模式的实现。
阅读全文