`
scholers
  • 浏览: 613875 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring与策略模式

阅读更多

                                               Spring与策略模式

 

一:策略模式的定义

策略模式是对算法的包装,把使用算法的责任和算法本身分隔开,委派给不同的对象管理。策略模式通常把一系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。

其类图如下:

 

 

 

如果是要用JAVA类来实现的策略模式,其源代码如下:

/**
 *
 * 策略执行
 * @author weique.lqf
 * @version $Id: Context.java, v 0.1 2014-2-9 下午2:32:56 weique.lqf Exp $
 */
public class Context {
    private Strategy stg;
 
    public Context(Strategy theStg) {
        this.stg = theStg;
    }
 
    public void doAction() {
        this.stg.testStrategy();
    }
}

 

 

策略接口:

/**
 *
 *
 * @author weique.lqf
 * @version $Id: Strategy.java, v 0.1 2014-2-9 下午2:32:17 weique.lqf Exp $
 */
public interface Strategy {
 
    void testStrategy();
}

 

实现类一:

package com.proxy.strategy.impl;
 
import com.proxy.strategy.Strategy;
 
public class PrintStrategy implements Strategy {
 
    public void testStrategy() {
        System.out.print("我要打印!!");
    }
 
}

 

实现类二:

package com.proxy.strategy.impl;
 
import com.proxy.strategy.Strategy;
 
public class WriteStrategy implements Strategy {
 
    public void testStrategy() {
        System.out.println("我要写字!!!");
    }
 
}

 

执行代码:

package com.proxy.strategy;
 
import com.proxy.strategy.impl.PrintStrategy;
 
public class StrategyClient {
 
    public static void main(String[] args) {
        Strategy stgA = new PrintStrategy();
        Context ct = new Context(stgA);
        ct.doAction();
    }
}

 

二:spring实现策略模式

         现在使用spring的系统可以说是多如牛毛,那么如何在spring模式下实现策略呢?

其实只需要稍微改造下就可以了,因为spring的核心之一就是IOC

首先修改Contex类:

package com.proxy.strategy;
 
public class ContextSpring {
    private Strategy stg;
 
    /**
     * Setter method for property <tt>stg</tt>.
     *
     * @param stg value to be assigned to property stg
     */
    public void setStg(Strategy stg) {
        this.stg = stg;
    }
 
    public void doAction() {
        this.stg.testStrategy();
    }
}

 

然后在spring配置文件里面配置,

   

<bean id="ct" class = "com.proxy.strategy.ContextSpring">
      <property name="stg" ref="writeStg"/>
   </bean>
   <bean id="writeStg" class = "com.proxy.strategy.impl.WriteStrategy"/>
   <bean id="printStg" class = "com.proxy.strategy.impl.PrintStrategy"/>

 

里面选择你将要注入的实现类,然后在执行的代码里面写这样:

package com.proxy.strategy;
 
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();
    }
 
}

 

看,这样就将spring引入了。

但是这样有好处也有坏处,如果我要根据不同的类型,比如说:合同是需要打印的,而情书是需要手写的。假设合同为类型2,情书为类型1,那我们怎么来自动适配?

三:高级版的spring策略模式

首先要修改Context类:

package com.proxy.strategy;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 *
 *
 * @author weique.lqf
 * @version $Id: ContextSpringFactory.java, v 0.1 2014-2-9 下午3:46:09 weique.lqf Exp $
 */
public class ContextSpringFactory {
 
    private Map<String, Strategy> stgMap = new HashMap<String, Strategy>();
 
    /**
     * Getter method for property <tt>stgMap</tt>.
     *
     * @return property value of stgMap
     */
    public Map<String, Strategy> getStgMap() {
        return stgMap;
    }
 
    /**
     * Setter method for property <tt>stgMap</tt>.
     *
     * @param stgMap value to be assigned to property stgMap
     */
    public void setStgMap(Map<String, Strategy> stgMap) {
        this.stgMap = stgMap;
    }
 
    public void doAction(String strType) {
        this.stgMap.get(strType).testStrategy();
    }
}

 

然后修改spring的配置文件:

   

<bean id="ctf" class = "com.proxy.strategy.ContextSpringFactory">
      <property name="stgMap"> 
         <map> 
              <entry key="1" value-ref="writeStg"/> 
              <entry key="2" value-ref="printStg"/>  
         </map> 
      </property> 
   </bean>

 

执行的入口类修改为:

package com.proxy.strategy;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class StrategySpringClientFactory {
    public static void main(String[] args) {
        //外部参数
        String type = "1";
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        ContextSpringFactory ctf = (ContextSpringFactory) context.getBean("ctf");
        ctf.doAction(type);
        //type 2
        type = "2";
        ctf.doAction(type);
    }
}

  

然后运行下,看看会有什么结果?

 

 

  • 大小: 27.4 KB
分享到:
评论
1 楼 accphc 2016-10-09  
策略工厂实现Spring的ApplicationContextAware接口,就可以直接根据bean的id来取得具体的策略了

相关推荐

    Spring下使用策略模式

    NULL 博文链接:https://zl4.iteye.com/blog/2333003

    spring事件驱动 + 策略模式应用

    技术: 1. spring事件驱动(ApplicationEventPublisher) 2. 策略模式处理事件 目的: 1. 通过event,代码逻辑异步处理 2. 通过策略模式,构建具体监听实现 3. 解耦 4. 容错(降低代码块错误风险)

    Spring项目整合策略模式~实战应用

    spring整合策略模式实战

    详解SpringBoot结合策略模式实战套路

    主要介绍了详解SpringBoot结合策略模式实战套路,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    spring中的基本设计模式

    本资源是spring的小例子程序,共包括以下7个: 数据访问对象模式(DAO) 工厂模式(factory) 模型视图控制器模式(MVC) ...策略模式(strategy) 模板模式(template) 另外还有一个关于动态代理的小例子

    Spring反射+策略模式Demo

    今次,则用反射+策略模式来重构一下代码,使之更加灵活。 如果有代码更好的优化方式,请下方留言。 码云:Demo地址 二、不使用反射的策略模式 抽象策略角色(接口) public interface MyStragtegy { String pl

    Java 经典设计模式讲解以及项目实战

    3 策略模式 4 模板方法模式 5 工厂方法模式 6 抽象工厂模式 7 建造者模式 8 代理模式 9 装饰模式 10 原型模式 11 委派模式 12 适配器模式 设计模式综合运用 1 门面+模版方法+责任链+策略 2 门面+模版方法+责任链+...

    掌握Spring设计模式:Java工程师必备指南

    策略模式和模板方法模式则分别提供了资源访问的灵活性和统一处理逻辑的框架。最后,责任链模式在Spring的AOP代理实现中发挥了重要作用,允许多个切面协调操作。这些模式共同构成了Spring框架的设计骨架,对于任何...

    40 Spring AOP策略模式使用及示例实战慕课专栏(1)1

    背景在现实生活中常常遇到实现某种目标存在多种策略可供选择的情况,例如,出行旅游可以乘坐飞机、乘坐火车、骑自行车或自己开私家车等,支付可以釆用支付宝、微信、银行卡

    策略模式干掉Spring中大片的 if else.docx

    利用策略模式取代代码中的if-else,提高代码可读性,利于维护扩展。

    Spring 设计模式总结1

    1.简单工厂 2.工厂方法 3.单例模式 4.适配器模式 5.装饰器模式 6.代理模式 7.观察者模式 8.策略模式 9.模版方法模式 1.简单工厂 2.工厂方

    策略模式消除if-else分支判断.zip

    使用策略模式和工厂模式彻底消除if-else分支

    spring security中文版

    即使用一个基于Spring3的web工程作为基础,以理解使用Spring Security3使其保证安全的概念和策略。 不管你是不是已经使用Spring Security还是只是对这个软件有兴趣,就都会在本书中得到有用的信息。 在本节的内容中,你...

    高级开发spring面试题和答案.pdf

    SPI 机制(Java SPI 实际上是“基于接口的编程+策略模式+配置文件”组合实现的动态加载机制), 很多地方有用到: AOP Spring的AOP的底层实现原理; 为什么jdk动态代理是必须是接口 两种动态代理的区别 AOP实现方式:...

    Spring高级之注解驱动开发视频教程

    视频详细讲解,需要的小...n 设计模式-RowMapper的策略模式 n 高级应用-NamedParameterJdbcTemplate的使用 n 源码分析-TransactionTemplate n 源码分析-DataSourceUtils n 源码分析-TransactionSynchronizationManager

    spring-resource:spring resouce code learn(Spring源码学习)

    太复杂的功能记录大概流程, 一些重要点注释实现细节和补充一些使用的例子spring 源码阅读记录IOCAOPMVCSpringMVC源码分析spring 实战设计模式结合spring的策略模式结合spring的管道模式特性实践spring事件机制-...

    spring4.3.2参考文档(英文)

    BeanFactory 使用控制反转 (IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。 Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 ...

    SpringBoot+策略模式 实现多种文件存储方式

    1)基于策略模式 2)支持本地文件存储和minio存储 3)可自定义扩展实现

    minio使用,poi解析,uid生成工具,策略工厂模式,模板管理完整功能,swagger集成,跨域,异常处理,分页等可用源代码

    5、策略工厂模式:用于不同业务逻辑的实现。 6、uid生成工具。 7、集成swagger在线接口文档。 8、文件上传功能。 9、excel文件解析功能:poi实现。 10、minio分布式存储:API封装并提供统一的请求接口。包括minio...

Global site tag (gtag.js) - Google Analytics