策略模式,是对一系列的算法进行了封装,使得它们之间可以相互替换。(神一般的语言,我真的无法体会)
示例代码如下:
package StrategyPolicy;
public interface IAlgorithm {
public void describe();
}
然后有三个alogrithm分别实现此接口:
package StrategyPolicy;
public class Algorithm1 implements IAlgorithm{
public void describe() {
System.out.println("algorithm1.");
}
}
package StrategyPolicy;
public class Algorithm2 implements IAlgorithm{
public void describe() {
System.out.println("algorithm2.");
}
}
package StrategyPolicy;
public class Algorithm3 implements IAlgorithm{
public void describe() {
System.out.println("algorithm3");
}
}
然后有个Context负责调用:
package StrategyPolicy;
public class AlgorithmContext {
private IAlgorithm algorithm;
public AlgorithmContext(int index){
switch(index){
case 1:this.algorithm = new Algorithm1();break;
case 2:this.algorithm = new Algorithm2();break;
case 3:this.algorithm = new Algorithm3();break;
}
}
public void describe() {
algorithm.describe();
}
}
接下来就是测试策略模式的代码:
package StrategyPolicy;
public class StrategyPolicyTest {
public static void main(String[] args){
AlgorithmContext ctx1 = new AlgorithmContext(1);
ctx1.describe();
AlgorithmContext ctx2 = new AlgorithmContext(2);
ctx2.describe();
AlgorithmContext ctx3 = new AlgorithmContext(3);
ctx3.describe();
}
}
反正我觉得策略模式和简单工厂还是挺像的,但是仔细想想,还是有差别:
如果是使用简单工厂的话,应该是这样写的:
public IAlgorithm getAlgorithm(int type){
//根据type,return 具体的Algorithm
}
然后,在测试的类中,直接用IAlgorithm的引用来接具体的Algorithm的对象,在利用这个引用调用describe方法。
感觉策略模式,就是将Algorithm连接口都不暴露给你了,直接根据你的要求,在Context里面进行使用。更加屏蔽了内部的细节。