设计模式之策略模式
设计模式之策略模式
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
主要解决:在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护
-
创建Strategy接口:
public interface Strategy {
void doOperation(int num1, int num2);
} -
创建实现接口的类:
public class MutiStrategy implements Strategy {
@Override
public void doOperation(int num1, int num2) {
System.out.println("num1 * num2 = "+num1 * num2);
}
}
public class AddStrategy implements Strategy {
@Override
public void doOperation(int num1, int num2) {
System.out.println(“num1+num2=”+num1+num2);
}
}
public class SubStrategy implements Strategy {
@Override
public void doOperation(int num1, int num2) {
System.out.println(“num1-num2=”+(num1-num2));
}
}
-
创建Context类(重点)
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void exeStrategy(int num1, int num2){
strategy.doOperation(num1,num2);
}
} -
编写测试类:
public class StrategyMain {
public static void main(String[] args) {
Context context = new Context(new AddStrategy());
context.exeStrategy(1,2);Context context1 = new Context(new SubStrategy()); context1.exeStrategy(2,1); Context context2 = new Context(new MutiStrategy()); context2.exeStrategy(2,4);
}
}