1. Java中策略模式
class="(抽象策略角色)接口">
public interface Strategy{
public int calculate(int a, int b);
}
public class AddStrategy implements Strategy{
public int calculate(int a, int b){
return a + b;
}
}
public class DivideStrategy implements Strategy{
public int calculate(int a, int b){
return a / b;
}
}
public class MultiplyStrategy implements Strategy{
public int calculate(int a, int b){
return a * b;
}
}
public class SubtractStrategy implements Strategy{
public int calculate(int a, int b){
return a - b;
}
}
public class Environment{
private Strategy strategy;
public Environment(Strategy strategy){
this.strategy = strategy;
}
public Strategy getStrategy(){
return strategy;
}
public void setStrategy(Strategy strategy){
this.strategy = strategy;
}
public int calculate(int a ,int b){
return strategy.calculate(a , b);
}
}
public class Client{
public static void main(String[] args){
AddStrategy addStrategy = new AddStrategy();
Environment environment = new Environment(addStrategy);
System.out.println(environment.calculate(3, 4));
SubtractStrategy subtractStrategy = new SubtractStrategy();
environment.setStrategy(subtractStrategy);
System.out.println(environment.calculate(3, 4));
MultiplyStrategy multiplyStrategy = new MultiplyStrategy();
environment.setStrategy(multiplyStrategy);
System.out.println(environment.calculate(3, 4));
DivideStrategy divideStrategy = new DivideStrategy();
environment.setStrategy(divideStrategy);
System.out.println(environment.calculate(3, 4));
}
}