首页 类库下载 java类库 Spring与策略模式

Spring与策略模式

Nov 07, 2016 pm 05:45 PM
spring

一:策略模式的定义

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

其类图如下:

97871e8f-0d17-33f9-968d-dd05769b67fa.jpg

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

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();  
    }  
}
登录后复制

策略接口:

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

实现类一:

Java代码

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

实现类二:

Java代码

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

执行代码:

Java代码

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类:

Java代码

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配置文件里面配置,

Xml代码

<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"/>
登录后复制

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

Java代码

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类:

Java代码

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的配置文件:

Xml代码

<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>
登录后复制

执行的入口类修改为:

Java代码

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);  
    }  
}
登录后复制

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

97871e8f-0d17-33f9-968d-dd05769b67fa.jpg

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

编程新范式,当Spring Boot遇上OpenAI 编程新范式,当Spring Boot遇上OpenAI Feb 01, 2024 pm 09:18 PM

2023年,AI技术已经成为热点话题,对各行业产生了巨大影响,编程领域尤其如此。人们越来越认识到AI技术的重要性,Spring社区也不例外。随着GenAI(GeneralArtificialIntelligence)技术的不断进步,简化具备AI功能的应用程序的创建变得至关重要和迫切。在这个背景下,"SpringAI"应运而生,旨在简化开发AI功能应用程序的过程,使其变得简单直观,避免不必要的复杂性。通过"SpringAI",开发者可以更轻松地构建具备AI功能的应用程序,将其变得更加易于使用和操作

利用Spring Boot以及Spring AI构建生成式人工智能应用 利用Spring Boot以及Spring AI构建生成式人工智能应用 Apr 28, 2024 am 11:46 AM

Spring+AI作为行业领导者,通过其强大、灵活的API和先进的功能,为各种行业提供了领先性的解决方案。在本专题中,我们将深入探讨Spring+AI在各领域的应用示例,每个案例都将展示Spring+AI如何满足特定需求,实现目标,并将这些LESSONSLEARNED扩展到更广泛的应用。希望这个专题能对你有所启发,更深入地理解和利用Spring+AI的无限可能。Spring框架在软件开发领域已经有超过20年的历史,自SpringBoot1.0版本发布以来已有10年。现在,无人会质疑,Spring

spring编程式事务有哪些实现方式 spring编程式事务有哪些实现方式 Jan 08, 2024 am 10:23 AM

spring编程式事务的实现方式:1、使用TransactionTemplate;2、使用TransactionCallback和TransactionCallbackWithoutResult;3、使用Transactional注解;4、使用TransactionTemplate和@Transactional结合使用;5、自定义事务管理器。

Java Spring怎么实现定时任务 Java Spring怎么实现定时任务 May 24, 2023 pm 01:28 PM

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

Spring Boot与Spring Cloud的区别与联系 Spring Boot与Spring Cloud的区别与联系 Jun 22, 2023 pm 06:25 PM

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

Spring如何设置事务隔离级别 Spring如何设置事务隔离级别 Jan 26, 2024 pm 05:38 PM

Spring设置事务隔离级别的方法:1、使用@Transactional注解;2、在Spring配置文件中设置;3、使用PlatformTransactionManager;4、在Java配置类中设置。详细介绍:1、使用@Transactional注解,在需要进行事务管理的类或方法上添加@Transactional注解,并在属性中设置隔离级别;​2、在Spring配置文件等等。

Spring 最常用的 7 大类注解,史上最强整理! Spring 最常用的 7 大类注解,史上最强整理! Jul 26, 2023 pm 04:38 PM

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

从零开始学Spring Cloud 从零开始学Spring Cloud Jun 22, 2023 am 08:11 AM

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

See all articles