一.策略模式的定义
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(来自百度百科)
二.策略模式组成
1.有一个策略接口:Istrategy
2.具体的实现类:StrategyOne、StrategyTwo、StrategyThree
3.对外提供的装有策略的容器:Content
4.策略模式的UML
三、实现代码
1.策略接口代码
package com.test.strategy;
public interface Istrategy {
public void operate();
}
2.接口实现代码
==================策略1====================
package com.test.strategy;
public class StrategyOne implements Istrategy {
@Override
public void operate() {
System.out.println("this is strategy one");
}
}
=================策略2======================
package com.test.strategy;
public class StrategyTwo implements Istrategy {
@Override
public void operate() {
System.out.println("this is strategy two");
}
}
=================策略3=====================
package com.test.strategy;
public class StrategyThree implements Istrategy {
@Override
public void operate() {
System.out.println("this is strategy three");
}
}
3.盛有策略的容器
package com.test.strategy;
public class Content {
public Istrategy strategy;
public Content(Istrategy strategy){
this.strategy = strategy;
}
public void operate(){
strategy.operate();
}
}
4.运行结果
四.应用场景
1.多个类唯一区别的就是实现方法的不通可以使用strategy
2.在不同的情形下使用不同的方法
3.隐藏具体实现方法,只提供容器调用