`
ahut9923
  • 浏览: 233521 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

结合Spring实现设计模式与面向接口编程(不断更新中...)

阅读更多

在学设计模式的时候,遇到的一个比较大的问题就是,虽然设计模式可以解决很多的重用性、解耦和的问题,但是最后在类之间建立关系的时候,还是需要显示的编写代码,在代码修改的时候,还是需要修改比较大量的代码,现在结合Spring,设计好类结构以后,就可以进行容器外类依赖注入,这是非常好的思想,不仅在更深程度实现了解耦和,同时让程序员更关注业务,而不是实现,真正实现面向接口的编程,可以说,纯设计模式是将类关系延迟到子类,而在Spring中,我认为类关系延迟到了容器外,或者直接说延迟到了XML文件中(不仅仅是XML配置文件,还有注解),通过简单的配置文件修改,就可以修改程序整个的类依赖关系.在我们实际开发过程中,我们完全可以设计好接口的结构,完全不用管实现类,在接口设计合理后,再进行实现,那么只需要添加配置文件的内容就可以实现程序的运转

 

工厂模式:

我们很了解这个模式,对于面向接口编程的思想,我们只需要定义接口,然后利用Spring进行装配,实现结束以后,再将实现类的类名写入配置文件中去。

工厂模式类图

 

 

 

              applicationContext.xml文件结构图


 

 

客户端使用代码:

                                                      view plaincopy to clipboardprint?
package org.ys.spring.factory;  
 
   
 
import org.springframework.context.ApplicationContext;  
 
import org.springframework.context.support.ClassPathXmlApplicationContext;  
 
   
 
public class Test {  
 
   
 
    public static void main(String[] args) {  
 
       ApplicationContext cs = new ClassPathXmlApplicationContext(  
 
              "applicationContext.xml");  
 
       IFactory bean = (IFactory) cs.getBean("factory");  
 
       bean.createProduct().operation();  
 
    }  
 

package org.ys.spring.factory;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

 

    public static void main(String[] args) {

       ApplicationContext cs = new ClassPathXmlApplicationContext(

              "applicationContext.xml");

       IFactory bean = (IFactory) cs.getBean("factory");

       bean.createProduct().operation();

    }

}
 

 

如果我们需要更改工厂或者产品,我们就可以在配置文件,将红色线内的字符串进行修改就可以,完全不用修改任何代码,

 

 

单例模式:

在默认的情况下,Spring中的bean都是单例模式,只是这个单例,不是通过代码限制,而是通过Spring容器限制,也就是说如果你想通过Spring获得对象时,这个对象是单例的。

 

 结构型模式中的组合模式

类图:

 

 相信大家也都很熟悉这个设计模式,applicationContext.xml文件结构图:

 

代码如下:

                       view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> 
    <bean id="factory" 
        class="org.ys.spring.composite.impl.TreeFactory"> 
    </bean> 
    <bean id="component" class="org.ys.spring.composite.IComponent" 
        factory-bean="factory" abstract="true"> 
    </bean> 
    <bean id="rootnode" 
        class="org.ys.spring.composite.impl.Component"> 
        <property name="list"> 
            <list value-type="org.ys.spring.composite.IComponent"> 
                <bean class="org.ys.spring.composite.impl.Component"></bean> 
                <bean class="org.ys.spring.composite.impl.Leaf"></bean> 
            </list> 
        </property> 
    </bean> 
</beans> 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 <bean id="factory"
  class="org.ys.spring.composite.impl.TreeFactory">
 </bean>
 <bean id="component" class="org.ys.spring.composite.IComponent"
  factory-bean="factory" abstract="true">
 </bean>
 <bean id="rootnode"
  class="org.ys.spring.composite.impl.Component">
  <property name="list">
   <list value-type="org.ys.spring.composite.IComponent">
    <bean class="org.ys.spring.composite.impl.Component"></bean>
    <bean class="org.ys.spring.composite.impl.Leaf"></bean>
   </list>
  </property>
 </bean>
</beans>

 

类代码如下:

IComponent:

                  view plaincopy to clipboardprint?
package org.ys.spring.composite;  
 
import java.util.List;  
 
/** 
 *  
 * @author T-Bag.& 
 * 
 */ 
public interface IComponent {  
 
    public void operation();  
 
    public List<IComponent> getChildren();  

package org.ys.spring.composite;

import java.util.List;

/**
 *
 * @author T-Bag.&
 *
 */
public interface IComponent {

 public void operation();

 public List<IComponent> getChildren();
}
 

ITreeFactory:

                 view plaincopy to clipboardprint?
package org.ys.spring.composite;  
 
/** 
 *  
 * @author T-Bag.& 
 *  
 */ 
public interface ITreeFactory {  
 
    public IComponent getTreeRoot();  

package org.ys.spring.composite;

/**
 *
 * @author T-Bag.&
 *
 */
public interface ITreeFactory {

 public IComponent getTreeRoot();
}
 

Component:

                view plaincopy to clipboardprint?
package org.ys.spring.composite.impl;  
 
import java.util.List;  
 
import org.ys.spring.composite.IComponent;  
 
/** 
 *  
 * @author T-Bag.& 
 *  
 */ 
public class Component implements IComponent {  
 
    List<IComponent> list = null;  
 
    public void setList(List<IComponent> l) {  
        this.list = l;  
    }  
 
    public List<IComponent> getChildren() {  
        return list;  
    }  
 
    public void operation() {  
 
    }  

package org.ys.spring.composite.impl;

import java.util.List;

import org.ys.spring.composite.IComponent;

/**
 *
 * @author T-Bag.&
 *
 */
public class Component implements IComponent {

 List<IComponent> list = null;

 public void setList(List<IComponent> l) {
  this.list = l;
 }

 public List<IComponent> getChildren() {
  return list;
 }

 public void operation() {

 }
}
 

Leaf:

                 view plaincopy to clipboardprint?
package org.ys.spring.composite.impl;  
 
import java.util.List;  
 
import org.ys.spring.composite.IComponent;  
 
/** 
 *  
 * @author T-Bag.& 
 *  
 */ 
public class Leaf implements IComponent {  
 
    public List<IComponent> getChildren() {  
        return null;  
    }  
 
    public void operation() {  
        System.out.println("i am leaf");  
    }  

package org.ys.spring.composite.impl;

import java.util.List;

import org.ys.spring.composite.IComponent;

/**
 *
 * @author T-Bag.&
 *
 */
public class Leaf implements IComponent {

 public List<IComponent> getChildren() {
  return null;
 }

 public void operation() {
  System.out.println("i am leaf");
 }
}
 

TreeFactory:

                view plaincopy to clipboardprint?
package org.ys.spring.composite.impl;  
 
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.ys.spring.composite.IComponent;  
import org.ys.spring.composite.ITreeFactory;  
 
/** 
 *  
 * @author T-Bag.& 
 *  
 */ 
public class TreeFactory implements ITreeFactory {  
 
    public IComponent getTreeRoot() {  
        ApplicationContext cs = new ClassPathXmlApplicationContext(  
                "applicationContext.xml");  
        return (IComponent) cs.getBean("rootnode");  
    }  

package org.ys.spring.composite.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ys.spring.composite.IComponent;
import org.ys.spring.composite.ITreeFactory;

/**
 *
 * @author T-Bag.&
 *
 */
public class TreeFactory implements ITreeFactory {

 public IComponent getTreeRoot() {
  ApplicationContext cs = new ClassPathXmlApplicationContext(
    "applicationContext.xml");
  return (IComponent) cs.getBean("rootnode");
 }
}
 

Test:

                 view plaincopy to clipboardprint?
package org.ys.spring.composite;  
 
import java.util.List;  
 
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
 
public class Test {  
 
    public static void main(String[] args) {  
        ApplicationContext cs = new ClassPathXmlApplicationContext(  
                "applicationContext.xml");  
        ITreeFactory f = (ITreeFactory) cs.getBean("factory");  
        IComponent treeRoot = f.getTreeRoot();  
        List<IComponent> children = treeRoot.getChildren();  
        System.out.println(children == null ? false : true);  
        if (children != null) {  
            for (IComponent i : children) {  
                i.operation();  
            }  
        }  
    }  

package org.ys.spring.composite;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

 public static void main(String[] args) {
  ApplicationContext cs = new ClassPathXmlApplicationContext(
    "applicationContext.xml");
  ITreeFactory f = (ITreeFactory) cs.getBean("factory");
  IComponent treeRoot = f.getTreeRoot();
  List<IComponent> children = treeRoot.getChildren();
  System.out.println(children == null ? false : true);
  if (children != null) {
   for (IComponent i : children) {
    i.operation();
   }
  }
 }
}
 

执行结果:

               view plaincopy to clipboardprint?
true 
i am leaf 
true
i am leaf

桥接模式:

看过《精通Spring Java 轻量级架构开发实践》的人,可能会知道,里面有一个利用桥接设计模式设计的一个邮件发送的例子,虽然它没有直接说用什么设计模式,但是我画了一张类图,大家从这里也可以看出,不仅可以看出使用了桥接设计模式,也可以看出使用Spring的好处。

 

 

 

大家可以看到这是典型的桥接设计模式,更重要的是,结合这种设计模式和Spring,客户端只需要和Spring打交道,不了解具体的实现类,而且可以通过配置文件的修改,改变具体的实现类,而不用手动注入


本想将所有的设计模式使用Spring实现一遍,但发现这些设计模式都有共通点,我就介绍了几种,其他的也都是一样的设计。只需要记住,面向接口、松耦合、依赖注入.

 

下面这个是最基本的一些Spring配置,保留下来,以后用到Spring就可以省去一些必要的配置,方便我们编程,将配置的时候省去

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    xmlns:context="http://www.springframework.org/schema/context
    xmlns:aop="http://www.springframework.org/schema/aop
    xmlns:tx="http://www.springframework.org/schema/tx
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-2.5.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
 
    <!-- tx: Spring注解的事务 --> 
    <!-- context: Spring注解的依赖注入 --> 
    <!-- aop: Spring注解的AOP --> 
 
    <context:annotation-config /> 
    <!-- 使用注解的方式实现依赖注入 --> 
    <!-- @Resource(name="")在字段上或者在set方法上 --> 
    <aop:aspectj-autoproxy /> 
    <!-- 使用注解的方式实现AOP编程 --> 
    <!-- 切面(类上): @Aspect --> 
    <!-- 切点(方法上): @Pointout(execution(* package..*.*(..))) public void anyMethod(){} --> 
    <!-- 通知(方法上): @Before("anyMethod") 代表在anyMethod这个切入点的前置通知--> 
    <!-- 将切面交给Spring --> 
    <bean id="aspectId" class="aspect class name"></bean> 
    <bean id="businessBean" class="business class name"></bean> 
    <!-- 然后用Spring获得这个businessBean,那么就可以了 --> 
 
    <!-- 使用XML方式实现依赖注入和AOP编程 --> 
 
    <!-- 提供一个类作为切面 --> 
    <bean id="aspectId2" class="aspect class name" /> 
    <!-- 进行AOP配置 --> 
    <aop:config> 
        <aop:aspect id="aspectI" ref="aspectId2"> 
            <aop:pointcut id="pointout" 
                expression="execution(* package..*.*(..))" /> 
            <aop:before method="切面类中的方法" pointcut-ref="pointout" /> 
            <aop:after-throwing method="抛出异常后执行" 
                pointcut-ref="pointout" /> 
        </aop:aspect> 
    </aop:config> 
 
    <!-- 使用XML进行依赖注入 --> 
    <bean id="factory" 
        class="org.ys.spring.composite.impl.TreeFactory"> 
    </bean> 
    <bean id="component" class="org.ys.spring.composite.IComponent" 
        factory-bean="factory" abstract="true" factory-method="getTreeRoot"> 
    </bean> 
    <bean id="rootnode" 
        class="org.ys.spring.composite.impl.Component"> 
        <property name="list"> 
            <list value-type="org.ys.spring.composite.IComponent"> 
                <bean class="org.ys.spring.composite.impl.Component"></bean> 
                <bean class="org.ys.spring.composite.impl.Leaf"></bean> 
            </list> 
        </property> 
    </bean> 
 
    <!-- Spring结合JDBC --> 
    <!-- 基于XML方法 --> 
    <bean id="dataSource" 
        class="org.apache.commons.dbcp.BasicDataSource" 
        destroy-method="close"> 
        <property name="driverClassName" value="驱动的包名加类名"></property> 
        <property name="url" 
            value="jdbc:mysql://localhost:8080/databaseName"> 
        </property> 
        <property name="username" value="root"></property> 
        <property name="password" value="***"></property> 
        <property name="initialSize" value="10"></property> 
        <property name="maxActive" value="100"></property> 
        <property name="maxIdle" value="20"></property><!-- 现在有500个空闲,释放连接的数,最多剩下20个 --> 
        <property name="minIdle" value="1"></property><!-- 最少链接的数,就算再少,也要有1个 --> 
    </bean> 
    <!-- Spring事务管理器 --> 
    <bean id="txManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
        <property name="dataSource" ref="dataSource"></property> 
    </bean> 
 
    <!-- Spring与JDBC使用注解 --> 
    <tx:annotation-driven transaction-manager="txManager" /> 
    <!-- 接下来就可以进行进行数据库的增删改查的操作了,将DAO的实现类交给Spring --> 
    <bean id="dao" class="dao class impl name"> 
        <property name="dataSource" ref="dataSource"></property> 
        <!-- 在dao实现类中,对DataSource变量进行注入 --> 
    </bean> 
    <!-- 然后就可以使用JdbcTemplate进行JDBC操作  
        JdbcTemplate template = new JdbcTemplate(dataSource);  
        //保存  
        template.update("insert into person values(?, ?)", new Object[]{1, "name"}, new int[]{java.sql.Types.INT, java.sql.Types.VARCHAR});  
        template.update("update person set name=? ", new Object[]{"name"}, new int[]{java.sql.Types.VARCHAR});  
        //查找  
        Object o = template.queryForObject("select * from person where id= ?", new Object[]{2}, new int[]{java.sql.Types.INT}, new RowMapper(){  
                public Object mapRow(ResultSet set, int index) {  
                    Person p = new Person();  
                    从set中取得信息放入p  
                    return p;  
                }  
            }  
        );  
        queryForObject返回一个对象  
        query返回多个对象,实际上返回List对象  
        queryFor...返回对应类型  
          
        如果没有事务管理器,那么方法中的每条语句都会在自身的事务中执行,所以在类上加上  
        @Transactional  
        那么在每个方法都是事务级的  
但是当需要在某个具体的方法上加上注解的时候,则涉及到事务的一些属性  
比如在方法上加上@Transactional(readonly=true,rollBackFor=Exception.class, propagation=Propagation.NOT_SUPPORT,isolation=Isolation.READ_COMMITTED)  
其中:readonly代表这个事务方法是只读的,不会插入修改,对于这样的方法,设置为true可以提高效率  
rollBackFor代表回滚原因,这里代表异常是Exception的回滚  
propagation代表事务传播方式,个人认为其主要关注点在于嵌套事务的处理方法。  
isolation就是代表事务的隔离级别  
 
 
 
    --> 
</beans>


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/neusoftware_20063500/archive/2009/04/18/4090299.aspx

分享到:
评论

相关推荐

    Java/JavaEE 学习笔记

    第六章 设计原则与模式..................307 EJB学习笔记..................314 EJB前言................314 EJB2.0.....315 第一章 EJB介绍 .315 第二章 First EJB....318 第三章 EJB原理.320 第四章 Session ...

    J2EE学习笔记(J2ee初学者必备手册)

    第六章 设计原则与模式..................307 EJB学习笔记..................314 EJB前言................314 EJB2.0.....315 第一章 EJB介绍 .315 JavaEE@xuxiang 5 Java/JavaEE学习笔记Jonny xuxiang5612@sina.com...

    Java 面试宝典

    23、java 中实现多态的机制是什么? ......................................................................... 17 24、abstract class 和 interface 有什么区别? ...............................................

    Spring攻略(第二版 中文高清版).part1

    10.6 使用BlazeDS和Spring消费面向消息的服务 421 10.6.1 问题 421 10.6.2 解决方案 422 10.6.3 工作原理 422 10.7 将依赖注入带给你的ActionScript客户 434 10.7.1 问题 434 10.7.2 解决方案 434 ...

    Spring攻略(第二版 中文高清版).part2

    10.6 使用BlazeDS和Spring消费面向消息的服务 421 10.6.1 问题 421 10.6.2 解决方案 422 10.6.3 工作原理 422 10.7 将依赖注入带给你的ActionScript客户 434 10.7.1 问题 434 10.7.2 解决方案 434 ...

    Spring基础与快速入门

    3 IOC:控制反转,谓之“依赖关系的转移”,如果以前都是依赖于实现,那么现在反转为依赖于抽象吧,其实它的核心思想就是要面向接口编程,至于何谓接口何谓抽象,以及它们的好处,多看看设计模式吧,这里就不费口舌...

    Spring AOP源码深度解析:掌握Java高级编程核心技术

    Spring AOP(面向切面编程)是Java高级编程中的重要组成部分,它允许程序员以声明的方式处理关注点(例如日志、事务管理等),而不是通过硬编码。本文深入分析了Spring AOP的实现机制,让读者能够更好地理解和应用这...

    Spring面试题

    下一个最高级抽象是 BeanFactory 接口,它是工厂设计模式的实现,允许通过名称创建和检索对象。BeanFactory 也可以管理对象之间的关系。 BeanFactory 支持两个对象模型。 □ 单态 模型提供了具有特定名称的对象的...

    springCloud

    二:服务介绍: 1) 服务的注册与发现 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理、服务发现、断路器、智能路由、微代理、控制总线、全局锁、决策竞选、...

    javaEE j2ee 大学考试题库, j2ee开发面试题库2

    1. 下面哪个选项不属于 MVC 设计模式的三个核心模块( ) A. 模型 B. 视图 C. 数据库连接 D. 控制器 2. Mybatis 的核心处理类是( ) A. SqlSessionFactory B. sql C. SqlSession D. SqlSessionFactoryBuilder 3. ...

    spring+struts2+hibernate框架说明

    Spring 提供了管理业务对象的一致方法,并鼓励注入对接口编程而不是对类编程的良好习惯,使我们的产品在最大程度上解耦。Hibernate 是用来持久化数据的,提供了完全面向对象的数据库操作。Hibernate对JDBC进行了非常...

    代码随想录最新第三版-最强八股文

    Java基础、Java内存模型、Java面向对象、Java集合体系、接口、Lambda表达式、类加载机制、内部类、代理类、Java并发、JVM、Java后端编译、Spring 3. Go defer底层原理、goroutine、select实现机制 4. 算法学习 数组...

    Spring+MVC+Mybatis 书城项目

    Spring MVC: Spring MVC是Spring框架的一个模块,它实现了MVC(模型-视图-控制器)设计模式,用于构建Web应用。Spring MVC允许你将应用的逻辑、数据和用户界面分离,使得代码更加清晰和易于维护。 MyBatis: MyBatis...

    java面试题

    62. java中实现多态的机制是什么? 42 63. 垃圾回收器的基本原理是什么?垃圾回收器可以马上回收内存吗?有什么办法主动通知虚拟机进行垃圾回收? 42 63.1. 判断该对象是否是时候可以收集方法 43 63.1.1. 引用计数 ...

    asp.net知识库

    与DotNet数据对象结合的自定义数据对象设计 (二) 数据集合与DataTable 与DotNet数据对象结合的自定义数据对象设计 (一) 数据对象与DataRow ASP.NET中大结果集的分页[翻译] .net 2.0 访问Oracle --与Sql Server的...

    weixin135房屋租赁管理系统的设计与实现+ssm--论文pf.rar

    Spring MVC:作为Spring的一个模块,提供了构建Web应用程序的MVC(模型-视图-控制器)设计模式的完整实现。 MyBatis:一个优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射,并且避免了几乎所有的JDBC代码...

    领域驱动设计与模式实战

    10.4 面向方面编程 10.4.1 热门话题有哪些 10.4.2 AOP术语定义 10.4.3 .NET中的AOP 10.4.4 小结 10.5 小结 第11章 关注UI 11.1 提前结语 11.2 模型-视图-控制器模式 11.2.1 示例:Joe的Shoe Shop程序 11.2.2 通过...

    practice:知识梳理:数据结构和算法,leetcode解题记录,手写生产者-消费者模型,SpringAOP,Springboot自定义注释解,异常异常处理,整合Mybatis,整合Redis,mybatis逆向工程,死锁,同步锁,读-写同步锁,BIO,NIO,AIO,Netty服务,客户端,ThreadLocal使用,23种设计模式(未完待续...),生成XML文件,接口并发测试,Kafka生产者消费者示例(持续更新)。 ..)

    JUC线程池和Spring提供的线程池,jdk 1.8中的日期时间API,数据结构中图的实现及操作和广度优先遍历/深度优先遍历(其他待完善),生成XML文件工具类,防止XSS攻击解决方案,mybatis逆向工程,接口并发测试,BIO,...

Global site tag (gtag.js) - Google Analytics