策略,指的是可以实现目标的方案集合
public interface IStrategy {
void operate();
}
public class AStrategy implements IStrategy {
public void operate() {
System.out.println("A策略");
}
}
public class BStrategy implements IStrategy {
public void operate() {
System.out.println("B策略");
}
}
public class CStrategy implements IStrategy {
public void operate() {
System.out.println("C策略");
}
}
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy=strategy;
}
public void operate(){
strategy.operate();
}
}
public class StrategyMain {
public static void main(String[] args) {
Context context;
context=new Context(new AStrategy());
context.operate();
context=new Context(new BStrategy());
context.operate();
context=new Context(new CStrategy());
context.operate();
}
}
策略模式的使用场景,SpringIoc、Spring的事务管理机制就是典型的策略模式