策略模式与简单工厂模式原理上有许多相似的地方,都是利用java的继承和多态实现。在这里贴上代码:
抽象父类:
public abstract class Operation {
protected double numberA;
protected double numberB;
public double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public Operation(double numberA, double numberB) {
super();
this.numberA = numberA;
this.numberB = numberB;
}
public abstract double getResult();
}
加法子类:
public class OperationAdd extends Operation{
public OperationAdd(double numberA, double numberB) {
super(numberA, numberB);
}
@Override
public double getResult() {
return numberA+numberB;
}
}
策略类:
public class Context {
private Operation op;
public Context(Operation op){
this.op=op;
}
public double getResult(){
return op.getResult();
}
junit测试:
@Test
public void test1(){
Context context=new Context(new OperationAdd(1,2));
System.out.println(context.getResult());
}
}
通过上面的代码,相信可以看出策略模式封装了算法,客户端只需要传入一个对象,到底使用那些算法由传入的对象来决定。
与简单工厂模式的区别:工厂模式是通过传入的参数获得对象,也就是工厂给你生产对象。策略模式则是你自己创建对象,传递对象。看到这里,可以发现这两者是可以结合在一起的,工厂模式创建对象,接着策略模式接收对象。具体可以看:程杰的《大话设计模式》