1. 策略模式概述
① 什么是java的策略模式?
- 本人喜欢看晋江言情小说,小说更新到一定章节就需要付费,这时有不同的充值方式。
- 如果让我去实现,可能会使用
if ... else
语句或者switch ... case
语句,整个充值方式的代码显得很长,一点都不简洁。
- 同一个行为,在不同的情况下有不同的算法策略,客户端在运行时根据情况决定使用某一具体算法策略。
- 此时,我们可以建立具有不同策略的对象,使用时再根据情况传入具体的策略对象。
② 策略模式的类图
- 抽象策略(Strategy): 接口或抽象类,提供策略的执行接口。
- 具体策略(ConcreteStrategy): 实现或继承抽象策略,根据情况,实现某种特定策略的代码逻辑。
- 上下文类(Context): 策略对象作为其内部对象,根据需要传入某个具体的策略对象,从而执行具体的策略。
2. 策略模式编程实例
① 单纯的策略模式
- 创建抽象策略的接口或抽象类,提供策略的执行入口。
- 创建多个具体策略类,实现或继承抽象策略,根据情况实现具体策略的代码逻辑。
- 创建上下文类,将抽象策略对象作为内部对象。
- 使用时,根据需要创建具体策略对象,将其传入上下文类中,然后调用策略执行方法执行对应策略。
- 小明准备去姑姑家做客,出发前他制定了不同的出行方案:晴天,骑自行车;雨天,做公交车;如果临时有事耽搁,出门太晚,就打出租车。
- 代码如下:
interface Go_out{
void execute();
}
class Go_outWithBike implements Go_out{
@Override
public void execute() {
System.out.println("今天天气好,骑自行车出门。");
}
}
class Go_outWithBus implements Go_out{
@Override
public void execute() {
System.out.println("今天下雨了,做公交出门。");
}
}
class Go_outWithTaxi implements Go_out{
@Override
public void execute() {
System.out.println("今天出门晚了,姑姑都在等我吃饭了,打车出门。");
}
}
class Contex{
private Go_out strategy;
public Go_out getStrategy() {
return strategy;
}
public void setStrategy(Go_out strategy) {
this.strategy = strategy;
}
public void doAction(){
if (strategy!=null){
strategy.execute();
}
}
}
public class Strategy {
public static void main(String[] args){
Go_out strategy=new Go_outWithBike();
Contex contex = new Contex();
contex.setStrategy(strategy);
contex.doAction();
}
}
② 策略模式与Spring结合
- 在Spring的xml文件中为Context注入实例:
<bean id="context" class = "lucy.service.impl.Context">
<property name="strategy" ref="strategyA"/>
</bean>
<bean id="strategyA" class = "lucy.impl.StrategyA"/>
<bean id="strategyB" class = "lucy.impl.StrategyB"/>
- 通过
ClassPathXmlApplicationContext
上下文获取xml中配置的上下文bean:context
,然后context调用doAction()
方法执行配置好的策略A。
package lucy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StrategySpringClient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
ContextSpring ct = (ContextSpring) context.getBean("ct");
ct.doAction();
}
}
3. 策略模式总结
- 良好的扩展性: 新增一种策略,只需要创建新的具体策略类即可;如果某种策略不需要了,可以直接剔除即可。
- 良好的封装性: 具体策略对象的调用封装在Context类中,客户端根据需要传递具体策略对象即可。
- 避免了简单工厂模式中的
if ... else
多重条件判断。
- 使用者必须知道有哪些策略类,并自行决定使用哪一个策略类。
- 策略模式将每一种策略都单独设计成一个具体策略类,如果策略很多的话,则会导致类的数目很多。