在软件开发中常常遇到这种情况,实现某一个功能有多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能。如何灵活地进行策略切换,这就是我们策略模式要做的。
Context算是一个上下文对象,来进行策略切换的中间类。
package strategy;
public interface Strategy {
public void operate();
}
package strategy;
public class Algorithm0 implements Strategy {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("算法0");
}
}
package strategy;
public class Algorithm1 implements Strategy {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("算法1");
}
}
package strategy;
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy=strategy;
}
public void operate(){
this.strategy.operate();
}
}
package strategy;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Context context=new Context();
Strategy algorithm0=new Algorithm0();
//可以切换算法
context.setStrategy(algorithm0);
context.operate();
Strategy algorithm1=new Algorithm1();
context.setStrategy(algorithm1);
context.operate();
}
}