码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式

时间:2019-03-25 23:26:38      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:sys   复杂   main   color   class   new   pre   his   ecif   

我觉得策略模式就像公司的饮水机

出水口只有一个,当你按热水时出热水,当你按冷水时出冷水,虽然出水口都是一个,但是你点击了不同的策略,就得到了不同的结果.

如何实现:

一个接口,多个实现类(就是策略类),一个调用者

 接口:

public interface getWater {
void getWater();
}
----------------策略类----------------
public class GetCoolWater implements GetWater {
@Override
public void getWater() {
System.out.println("取凉水");
}
}

public class GetHotWater implements GetWater {
@Override
public void getWater() {
System.out.println("取热水");
}
}
---------------调用类-------------------
public class RealGetWater {
public GetWater getWater;
public RealGetWater(GetWater getWater){
this.getWater = getWater;
}
public void realGetWater(){
getWater.getWater();
}
------------------测试-----------------
public class Test0 {
private static int CHOOSE_CODE = 0 ;
public static void main(String[] args) {
GetCoolWater getCoolWater = new GetCoolWater();
GetHotWater getHotWater = new GetHotWater();

RealGetWater realGetWater = new RealGetWater(CHOOSE_CODE == 1 ? getHotWater : getCoolWater);
realGetWater.getWater.getWater();
}
}
=======================================
结果表明:当choose_code为0时打印冷水,当choose_code为1时打印热水.
真正实现了通过选择不同的简单策略,获取不同的复杂结果!
这,就是策略模式.

在SpringApplication启动过程中,有一个方法createApplicationContext()也使用了策略模式,如下:
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
contextClass = Class.forName(this.webEnvironment
? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}

通过传入不同的contextClass对象(策略),可以创建完全不同的ApplicationContext对象(结果).



策略模式

标签:sys   复杂   main   color   class   new   pre   his   ecif   

原文地址:https://www.cnblogs.com/wangxuejian/p/10597312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!