策略模式:定义了一系列的算法,并将每一个算法封装起来,而且使他们可以相互替换,让算法独立于使用它的客户而独立变化。
1.策略接口
public interface Strategy {
void operate();
}
2.具体实现类
public class Strategy1 implements Strategy{
@Override
public void operate() {
System.out.println("我是策略1");
}
}
public class Strategy2 implements Strategy{
@Override
public void operate() {
System.out.println("我是策略2");
}
}
3.环境类
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void operate() {
if(null != this.strategy) {
this.strategy.operate();
}
}
public static void main(String[] args) {
Context c = new Context(new Strategy1());
c.operate();
c.setStrategy(new Strategy2());
c.operate();
}
}